import { NextRequest, NextResponse } from "next/server";
import { db, mealPlans, users, eq } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";
import { getMealPlanAccessById } from "@/lib/meal-plan-access";

type Params = { params: Promise<{ mealPlanId: string }> };

export async function GET(req: NextRequest, { params }: Params) {
  const { session, response } = await requireSessionOrApiKey(req);
  if (response) return response;
  const { mealPlanId } = await params;

  const access = await getMealPlanAccessById(mealPlanId, session!.user.id);
  if (!access) return NextResponse.json({ error: "Not found" }, { status: 404 });

  const plan = await db.query.mealPlans.findFirst({
    where: eq(mealPlans.id, mealPlanId),
    with: {
      entries: { with: { recipe: { with: { photos: true } } } },
    },
  });
  if (!plan) return NextResponse.json({ error: "Not found" }, { status: 404 });

  const owner = await db.query.users.findFirst({ where: eq(users.id, plan.userId) });

  return NextResponse.json({ ...plan, role: access.role, owner: owner ? { name: owner.name } : null });
}
