import { NextRequest, NextResponse } from "next/server";
import { validateScenarioConfig } from "@/lib/scenarios/model";
import { createScenario } from "@/lib/scenarios/queries";

export async function POST(
  request: NextRequest,
  props: { params: Promise<{ portfolioId: string }> },
) {
  const { portfolioId } = await props.params;
  if (!portfolioId || !/^\d+$/.test(portfolioId)) {
    return NextResponse.json({ error: "Invalid portfolioId" }, { status: 400 });
  }

  let body: unknown;
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
  }

  const b = body as Record<string, unknown>;
  const result = validateScenarioConfig({
    name: typeof b.name === "string" ? b.name : "",
    housingType: typeof b.housingType === "string" ? b.housingType : "",
    goal: typeof b.goal === "string" ? b.goal : "",
    goalValue: typeof b.goalValue === "string" ? b.goalValue : null,
    budgetPerProperty:
      typeof b.budgetPerProperty === "number" ? b.budgetPerProperty : null,
    exclusions: Array.isArray(b.exclusions)
      ? b.exclusions.filter((k): k is string => typeof k === "string")
      : [],
    fabricFirst: b.fabricFirst === true,
  });

  if (!result.ok) {
    const detail = Object.values(result.errors).join("; ");
    return NextResponse.json({ error: detail }, { status: 400 });
  }

  const id = await createScenario(BigInt(portfolioId), result.value);
  return NextResponse.json({ id: String(id) }, { status: 201 });
}
