import { NextResponse } from "next/server";

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

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 job = await repository.getArticleJob(jobId);
  if (!job) {
    return NextResponse.json({ error: "Job not found" }, { status: 404 });
  }

  try {
    const factCard = confirmedFactCardSchema.parse(await request.json());
    const brandTemplate = await repository.createBrandTemplate({
      brand_name:
        factCard.brand_names[0] ??
        factCard.company_short_names[0] ??
        factCard.company_full_name,
      company_full_name: factCard.company_full_name,
      company_short_names: factCard.company_short_names,
      product_names: factCard.product_names,
      target_industries: [factCard.target_industry],
      target_audience: [factCard.target_audience],
      verified_claims: factCard.core_claims,
      forbidden_claims: factCard.forbidden_claims,
      tone_rules: {
        official_site: "official brand voice",
        media_article: "objective third-party voice",
      },
    });
    const savedFactCard = await repository.saveFactCard(jobId, factCard);
    await repository.updateArticleJob(jobId, {
      brand_template_id: brandTemplate.id,
      status: "fact_confirmed",
    });

    return NextResponse.json({ brandTemplate, factCard: savedFactCard });
  } catch (error) {
    const message = error instanceof Error ? error.message : "Invalid fact card";
    return NextResponse.json({ error: message }, { status: 400 });
  }
}
