import {
  getSampleClassifications,
  getUnknownOverrides,
  setClassificationOverride,
} from "@/lib/bulkUpload/server";
import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { AuthOptions } from "@/app/api/auth/[...nextauth]/authOptions";
import { z } from "zod";

// Read-only: the classifier's resolved enums for the review sample's entries
// (field -> description -> value), plus the descriptions still classified
// `Unknown` portfolio-wide — the Finalise gate blocks until that list is empty
// and the user can resolve each via PATCH below (ADR-0004 #298, ADR-0006).
export async function GET(
  _request: NextRequest,
  { params }: { params: Promise<{ portfolioId: string; uploadId: string }> }
) {
  const session = await getServerSession(AuthOptions);
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { portfolioId, uploadId } = await params;
  const [classifications, unknown] = await Promise.all([
    getSampleClassifications(uploadId),
    getUnknownOverrides(portfolioId),
  ]);
  return NextResponse.json({ classifications, unknown }, { status: 200 });
}

const PatchSchema = z.object({
  field: z.string(),
  description: z.string(),
  value: z.string(),
});

// Correct one classification, written as a user override (source='user'). The
// edit is per-(portfolio, description), so it applies portfolio-wide (issue #299).
export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ portfolioId: string; uploadId: string }> }
) {
  const session = await getServerSession(AuthOptions);
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { portfolioId } = await params;

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

  try {
    const result = await setClassificationOverride(
      portfolioId,
      body.field,
      body.description,
      body.value,
    );
    if (result.kind === "invalid")
      return NextResponse.json({ error: result.reason }, { status: 422 });
    return NextResponse.json({ ok: true }, { status: 200 });
  } catch (error) {
    console.error("Failed to save classification override:", error);
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
