import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { AuthOptions } from "@/app/api/auth/[...nextauth]/authOptions";
import { z } from "zod";
import { normaliseRunFilters } from "@/lib/modellingRuns/model";
import { previewModellingRun } from "@/lib/modellingRuns/server";

const bodySchema = z.object({
  scenarioIds: z.array(z.string().regex(/^\d+$/)).min(1).max(50),
  filters: z
    .object({
      postcodes: z.array(z.string()).optional(),
      propertyTypes: z.array(z.string()).optional(),
      builtForms: z.array(z.string()).optional(),
      tagIds: z.array(z.union([z.string(), z.number()])).optional(),
    })
    .default({}),
});

// POST — dry-run counts from the backend (same resolution code path as the
// real run; the preview is a promise, not an estimate — ADR-0008).
export async function POST(
  request: NextRequest,
  props: { params: Promise<{ portfolioId: string }> },
) {
  const session = await getServerSession(AuthOptions);
  if (!session?.user?.email) {
    return NextResponse.json({ error: "Unauthorised" }, { status: 401 });
  }
  const { portfolioId } = await props.params;
  if (!/^\d+$/.test(portfolioId)) {
    return NextResponse.json({ error: "Invalid portfolio id" }, { status: 400 });
  }

  let body: z.infer<typeof bodySchema>;
  try {
    body = bodySchema.parse(await request.json());
  } catch {
    return NextResponse.json({ error: "Invalid body" }, { status: 400 });
  }
  const normalised = normaliseRunFilters(body.filters);
  if (!normalised.ok) {
    return NextResponse.json({ error: normalised.error }, { status: 400 });
  }

  try {
    const result = await previewModellingRun({
      portfolioId,
      scenarioIds: [...new Set(body.scenarioIds)],
      filters: normalised.filters,
    });
    return NextResponse.json(result);
  } catch (err) {
    console.error("POST /modelling-runs/preview error:", err);
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
