import { NextResponse } from "next/server";
import { getDatabase } from "@/lib/database";
import log from "@/lib/logger";

export async function POST(req: Request) {
  try {
    const body = await req.json();
    log.debug("Approve recommendation request body", { body });

    const { recommendationId, status, approvedBy } = body;

    if (!recommendationId || !status) {
      log.error("Missing required fields", {
        recommendationId,
        status,
        receivedBody: body,
      });
      return NextResponse.json(
        { error: "Recommendation ID and status are required" },
        { status: 400 },
      );
    }

    const db = await getDatabase();

    // Update recommendation status
    const updates: any = {
      status,
      approvedAt: status === "approved" ? new Date() : undefined,
      approvedBy: status === "approved" ? approvedBy : undefined,
    };

    // Remove undefined keys
    Object.keys(updates).forEach(
      (key) => updates[key] === undefined && delete updates[key],
    );

    const updatedRecommendation = await db.updateRecommendation(
      recommendationId,
      updates,
    );

    if (!updatedRecommendation) {
      return NextResponse.json(
        { error: "Recommendation not found" },
        { status: 404 },
      );
    }

    // If approved, create a notification for the user
    if (status === "approved") {
      try {
        await db.createNotification({
          id: crypto.randomUUID(),
          userId: updatedRecommendation.userId,
          title: "Recommendation Approved! 🎉",
          message:
            "Your AI-powered fitness recommendation has been approved by your trainer. Check it out now!",
          type: "system",
          read: false,
        });

        log.info("Notification created for approved recommendation", {
          recommendationId,
          userId: updatedRecommendation.userId,
        });
      } catch (notificationError) {
        // Log error but don't fail the approval
        log.error("Failed to create notification", notificationError);
      }
    }

    return NextResponse.json({
      success: true,
      data: updatedRecommendation,
      meta: {
        timestamp: new Date().toISOString(),
      },
    });
  } catch (error) {
    log.error("Error approving recommendation", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 },
    );
  }
}
