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";
import { createInstacartShoppingListLink } from "@/lib/grocery-providers/instacart";
import { requireFeatureEnabledResponse } from "@/lib/feature-flags";

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

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

  const featureDenied = await requireFeatureEnabledResponse(session!.user.id, "grocery_delivery");
  if (featureDenied) return featureDenied;

  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);

  try {
    const result = await createInstacartShoppingListLink(payload);
    if (!result) return NextResponse.json({ error: "Instacart is not configured" }, { status: 501 });
    return NextResponse.json(result);
  } catch (err) {
    return NextResponse.json({ error: String(err instanceof Error ? err.message : err) }, { status: 501 });
  }
}
