import { NextResponse } from "next/server";

import { requireApiAccess } from "../../../../../../lib/api/auth";
import {
  GEO_RUBRIC_V1,
  scoreOptimizedArticle,
} from "../../../../../../lib/calibration/scoring";
import { getRepositoryFromRuntime } from "../../../../../../lib/db/repository";

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

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

  const { jobId } = await context.params;
  const repository = getRepositoryFromRuntime();
  const article = await repository.getLatestOptimizedArticle(jobId);
  const qaReport = await repository.getLatestQaReport(jobId);
  if (!article || !qaReport) {
    return NextResponse.json(
      { error: "Optimize the article before scoring calibration" },
      { status: 409 },
    );
  }

  await repository.saveRubricVersion(GEO_RUBRIC_V1);
  const resultVersion = await repository.findResultVersionForArticleRevision(
    jobId,
    article.revision ?? 1,
  );
  const scoringRun = await repository.saveScoringRun(
    scoreOptimizedArticle({
      jobId,
      article,
      qaReport,
      resultVersionId: resultVersion?.id ?? null,
    }),
  );

  return NextResponse.json({ scoringRun }, { status: 201 });
}
