import { NextResponse } from "next/server";

import { requireApiAccess } from "../../../../../../../lib/api/auth";
import { resultVersionPublicationInputSchema } from "../../../../../../../lib/cases/validation";
import { getRepositoryFromRuntime } from "../../../../../../../lib/db/repository";

interface RouteContext {
  params: Promise<{ caseId: string; versionId: string }>;
}

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

  const { caseId, versionId } = await context.params;
  const repository = getRepositoryFromRuntime();
  const version = await repository.getOptimizationResultVersion(versionId);
  if (!version || version.case_id !== caseId) {
    return NextResponse.json(
      { error: "Result version not found" },
      { status: 404 },
    );
  }

  return NextResponse.json({
    publications: await repository.listPublicationRecordsForResultVersion(
      version.id,
    ),
  });
}

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

  const { caseId, versionId } = await context.params;
  const repository = getRepositoryFromRuntime();
  const version = await repository.getOptimizationResultVersion(versionId);
  if (!version || version.case_id !== caseId) {
    return NextResponse.json(
      { error: "Result version not found" },
      { status: 404 },
    );
  }

  const input = resultVersionPublicationInputSchema.parse(await request.json());
  const publication = await repository.createPublicationRecord({
    result_version_id: version.id,
    job_id: version.article_job_id,
    revision: version.article_revision,
    publish_target: input.publish_target,
    url: input.url,
    published_at: input.published_at,
    status: "published",
    notes: input.notes,
  });

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