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";
import type { QaReport } from "../../../../../lib/domain/types";

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 = publication.result_version_id
    ? await repository.getLatestScoringRunForResultVersion(
        publication.result_version_id,
      )
    : publication.job_id && publication.revision
      ? await repository.getLatestScoringRun(
          publication.job_id,
          publication.revision,
        )
      : null;
  const qaReport: QaReport | null = publication.job_id
    ? await repository.getLatestQaReport(publication.job_id)
    : scoringRun?.case_type === "human_copy"
      ? {
          overall_status: "pass",
          checks: [],
        }
      : null;
  const manualInput = await request.json();

  if (!publication.result_version_id && (!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,
      }),
    );
    if (!scoringRun || !qaReport) {
      return NextResponse.json(
        { snapshot, calibrationEvent: null },
        { status: 201 },
      );
    }
    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 });
  }
}
