import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { z } from "zod";

import { AuthOptions } from "@/app/api/auth/[...nextauth]/authOptions";
import { upsertUprnCorrection } from "@/lib/bulkUpload/addressMatches";

// Confirm one flagged combiner row (ADR-0057): either assign a UPRN chosen from
// OS Places, or assert the address has none. Keyed by `source_row_id` (there is
// no property.id yet — the finaliser creates identities). Upsert semantics, so
// re-confirming overwrites. The confirmation is overlaid onto the combiner CSV
// at dispatchFinaliser.
const AssignSchema = z.object({
  sourceRowId: z.string().min(1),
  uprn: z.string().regex(/^\d+$/, "UPRN must be numeric"),
  address: z.string().min(1),
  postcode: z.string().min(1),
});
const NoUprnSchema = z.object({
  sourceRowId: z.string().min(1),
  markedNoUprn: z.literal(true),
});
const BodySchema = z.union([NoUprnSchema, AssignSchema]);

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ portfolioId: string; uploadId: string }> },
) {
  const session = await getServerSession(AuthOptions);
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { uploadId } = await params;
  const parsed = BodySchema.safeParse(await request.json().catch(() => null));
  if (!parsed.success) {
    return NextResponse.json(
      { error: parsed.error.issues[0]?.message ?? "Invalid request" },
      { status: 400 },
    );
  }

  await upsertUprnCorrection(uploadId, parsed.data, session.user?.email ?? undefined);
  return NextResponse.json({ ok: true }, { status: 200 });
}
