import { NextResponse } from "next/server";

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

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

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

  const { jobId } = await context.params;
  const repository = getRepositoryFromRuntime();
  return NextResponse.json({
    publications: await repository.listPublicationRecords(jobId),
  });
}

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);
  if (!article?.revision) {
    return NextResponse.json(
      { error: "Optimize the article before registering publication" },
      { status: 409 },
    );
  }

  try {
    const input = publicationInputSchema.parse(await request.json());
    const publication = await repository.createPublicationRecord({
      job_id: jobId,
      revision: article.revision,
      platform: input.platform,
      url: input.url,
      published_at: input.published_at,
      status: "published",
      notes: input.notes,
    });

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