import { NextResponse } from "next/server";

import { requireApiAccess } from "../../../../../lib/api/auth";
import { createManualPerformanceAdapter } from "../../../../../lib/calibration/manual-adapter";
import { createCalibrationEvent } from "../../../../../lib/calibration/scoring";
import { getRepositoryFromRuntime } from "../../../../../lib/db/repository";

interface RouteContext {
  params: Promise<{ publicationId: string }>;
}

export async function POST(request: Request, context: RouteContext) {
  const access = requireApiAccess(request);
  if (!access.ok) {
    return access.response;
  }

  const { publicationId } = await context.params;
  const repository = getRepositoryFromRuntime();
  const publication = await repository.getPublicationRecord(publicationId);
  if (!publication) {
    return NextResponse.json({ error: "Publication not found" }, { status: 404 });
  }

  const scoringRun = await repository.getLatestScoringRun(
    publication.job_id,
    publication.revision,
  );
  const qaReport = await repository.getLatestQaReport(publication.job_id);
  if (!scoringRun || !qaReport) {
    return NextResponse.json(
      { error: "Score the optimized revision before recording performance" },
      { status: 409 },
    );
  }

  try {
    const adapter = createManualPerformanceAdapter();
    const snapshot = await repository.savePerformanceSnapshot(
      await adapter.fetch({
        publication,
        window_label: "manual",
        manualInput: await request.json(),
      }),
    );
    const calibrationEvent = await repository.saveCalibrationEvent(
      createCalibrationEvent({ scoringRun, qaReport, snapshot }),
    );

    return NextResponse.json({ snapshot, calibrationEvent }, { status: 201 });
  } catch (error) {
    const message = error instanceof Error ? error.message : "Invalid performance";
    return NextResponse.json({ error: message }, { status: 400 });
  }
}
