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

export async function GET(request: Request) {
  try {
    const { userId: currentUserId } = await auth();
    if (!currentUserId) {
      return new NextResponse("Unauthorized", { status: 401 });
    }

    const { searchParams } = new URL(request.url);
    const targetUserId = searchParams.get("userId");

    const db = await getDatabase();

    // If no userId provided, check if staff and return all recommendations
    if (!targetUserId) {
      const currentUser = await db.getUserById(currentUserId);
      const isStaff =
        currentUser?.role === "admin" ||
        currentUser?.role === "superAdmin" ||
        currentUser?.role === "trainer";

      if (!isStaff) {
        return new NextResponse("User ID is required", { status: 400 });
      }

      const recommendations = await db.getAllRecommendations();
      return NextResponse.json({ recommendations });
    }

    // Check permissions: Users can view their own, Admins/Trainers can view anyone's
    const currentUser = await db.getUserById(currentUserId);
    const isStaff =
      currentUser?.role === "admin" ||
      currentUser?.role === "superAdmin" ||
      currentUser?.role === "trainer";

    if (currentUserId !== targetUserId) {
      if (!isStaff) {
        return new NextResponse("Forbidden", { status: 403 });
      }
    }

    let recommendations = await db.getRecommendationsByUserId(targetUserId);

    // Non-staff users should only see approved recommendations
    if (!isStaff) {
      recommendations = recommendations.filter(
        (rec: any) => rec.status === "approved",
      );
    }

    return NextResponse.json(recommendations);
  } catch (error) {
    console.error("Error fetching recommendations:", error);
    return new NextResponse("Internal Server Error", { status: 500 });
  }
}

export async function POST(request: Request) {
  try {
    const { userId: currentUserId } = await auth();
    if (!currentUserId) {
      return new NextResponse("Unauthorized", { status: 401 });
    }

    const db = await getDatabase();
    const currentUser = await db.getUserById(currentUserId);
    const isStaff =
      currentUser?.role === "admin" ||
      currentUser?.role === "superAdmin" ||
      currentUser?.role === "trainer";

    if (!isStaff) {
      return new NextResponse("Forbidden", { status: 403 });
    }

    const body = await request.json();
    const {
      userId,
      fitnessProfileId,
      recommendationText,
      activityPlan,
      dietPlan,
      status,
      type,
      content,
    } = body;

    // Handle AI Plan (Legacy/Specific)
    if (recommendationText && activityPlan && dietPlan && fitnessProfileId) {
      const recommendation = await db.createRecommendation({
        id: crypto.randomUUID(),
        userId,
        fitnessProfileId,
        type: "ai_plan",
        recommendationText: recommendationText,
        activityPlan,
        dietPlan,
        status: status || "pending",
      });
      return NextResponse.json(recommendation);
    }

    // Handle User Goal (Generic)
    if (type && content) {
      const recommendation = await db.createRecommendation({
        id: crypto.randomUUID(),
        userId,
        type,
        recommendationText: content,
        status: status || "pending",
      });
      return NextResponse.json(recommendation);
    }

    return NextResponse.json("Missing required fields", { status: 400 });
  } catch (error) {
    log.error("Failed to create recommendation", error);
    return new NextResponse("Internal Server Error", { status: 500 });
  }
}

export async function PUT(request: Request) {
  try {
    const { userId: currentUserId } = await auth();
    if (!currentUserId) {
      return new NextResponse("Unauthorized", { status: 401 });
    }

    const body = await request.json();
    const { id, status, recommendationText, activityPlan, dietPlan, content } =
      body;

    if (!id) {
      return new NextResponse("Recommendation ID is required", { status: 400 });
    }

    const db = await getDatabase();

    const updated = await db.updateRecommendation(id, {
      ...(status && { status }),
      ...(recommendationText && { recommendationText }),
      ...(content && { recommendationText: content }),
      ...(activityPlan && { activityPlan }),
      ...(dietPlan && { dietPlan }),
    });

    return NextResponse.json(updated);
  } catch (error) {
    log.error("Failed to update recommendation", error);
    return new NextResponse("Internal Server Error", { status: 500 });
  }
}
