import { NextRequest, NextResponse } from "next/server";
import { db, shoppingLists, eq } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";
import { getShoppingListAccess } from "@/lib/shopping-list-access";
import { buildGroceryExportPayload } from "@/lib/grocery-export";

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

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

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

  const list = await db.query.shoppingLists.findFirst({
    where: eq(shoppingLists.id, id),
    with: { items: true },
  });
  if (!list) return NextResponse.json({ error: "Not found" }, { status: 404 });

  const payload = buildGroceryExportPayload(list);
  return NextResponse.json(payload);
}
