import { NextRequest, NextResponse } from "next/server";
import {
  deleteScenarioIfUnmodelled,
  renameScenario,
} from "@/lib/scenarios/queries";

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

function parseIds(portfolioId: string, scenarioId: string) {
  if (!/^\d+$/.test(portfolioId) || !/^\d+$/.test(scenarioId)) return null;
  return { pid: BigInt(portfolioId), sid: BigInt(scenarioId) };
}

/** Rename only — a Scenario's configuration is immutable (ADR-0003). */
export async function PATCH(request: NextRequest, props: Params) {
  const { portfolioId, scenarioId } = await props.params;
  const ids = parseIds(portfolioId, scenarioId);
  if (!ids) return NextResponse.json({ error: "Invalid id" }, { status: 400 });

  let body: { name?: unknown };
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
  }
  const name = typeof body.name === "string" ? body.name.trim() : "";
  if (!name) {
    return NextResponse.json({ error: "Name is required" }, { status: 400 });
  }

  const renamed = await renameScenario(ids.pid, ids.sid, name);
  if (!renamed) {
    return NextResponse.json({ error: "Scenario not found" }, { status: 404 });
  }
  return NextResponse.json({ name });
}

export async function DELETE(request: NextRequest, props: Params) {
  const { portfolioId, scenarioId } = await props.params;
  const ids = parseIds(portfolioId, scenarioId);
  if (!ids) return NextResponse.json({ error: "Invalid id" }, { status: 400 });

  const result = await deleteScenarioIfUnmodelled(ids.pid, ids.sid);
  if (result.outcome === "deleted") {
    return NextResponse.json({ deleted: true });
  }
  if (result.outcome === "has_plans") {
    return NextResponse.json(
      {
        error: `There are ${result.plansCount} properties with plans in this scenario, so it can't be deleted. Contact a Domna administrator to remove the plans first.`,
        plansCount: result.plansCount,
      },
      { status: 409 },
    );
  }
  return NextResponse.json({ error: "Scenario not found" }, { status: 404 });
}
