import { type NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { requireSessionOrApiKey } from "@/lib/api-auth";
import { db, recipes, eq, and, inArray } from "@epicure/db";
import { recipeToMarkdown } from "@/lib/markdown/recipe";
import { requireFeatureEnabledResponse } from "@/lib/feature-flags";

const ExportSchema = z.object({
  ids: z.array(z.string()).min(1).max(100),
});

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

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

  const body = ExportSchema.safeParse(await req.json());
  if (!body.success) return NextResponse.json({ error: "Invalid request" }, { status: 400 });

  const owned = await db.query.recipes.findMany({
    where: and(inArray(recipes.id, body.data.ids), eq(recipes.authorId, session!.user.id)),
    with: {
      ingredients: { orderBy: (t, { asc }) => asc(t.order) },
      steps: { orderBy: (t, { asc }) => asc(t.order) },
      batchDishes: { orderBy: (t, { asc }) => asc(t.order) },
    },
  });

  if (owned.length === 0) return NextResponse.json({ error: "Not found" }, { status: 404 });

  const byId = new Map(owned.map((r) => [r.id, r]));
  const ordered = body.data.ids.flatMap((id) => (byId.has(id) ? [byId.get(id)!] : []));

  const markdown = ordered
    .map((recipe) =>
      recipeToMarkdown({
        title: recipe.title,
        description: recipe.description,
        baseServings: recipe.baseServings,
        prepMins: recipe.prepMins,
        cookMins: recipe.cookMins,
        difficulty: recipe.difficulty,
        sourceUrl: recipe.sourceUrl,
        ingredients: recipe.ingredients,
        steps: recipe.steps,
        isBatchCook: recipe.isBatchCook,
        batchDishes: recipe.batchDishes,
      })
    )
    .join("\n---\n\n");

  return NextResponse.json({ markdown });
}
