import { NextRequest, NextResponse } from "next/server";
import { rewriteSubmission } from "@/lib/ai/rewrite-pipeline";

export const runtime = "nodejs";
export const maxDuration = 300;

function bearerToken(req: NextRequest): string | null {
  const h = req.headers.get("authorization") || "";
  const m = h.match(/^Bearer\s+(.+)$/i);
  return m ? m[1].trim() : null;
}

function checkAuth(req: NextRequest): boolean {
  const wantBearer = process.env.BB_INGEST_BEARER || "";
  const wantInternalKey = process.env.BB_INTERNAL_INGEST_KEY || "";
  if (!wantBearer && !wantInternalKey) return false;
  if (wantBearer && bearerToken(req) === wantBearer) return true;
  if (wantInternalKey && (req.headers.get("x-internal-key") || "") === wantInternalKey) return true;
  return false;
}

export async function POST(req: NextRequest) {
  try {
    if (!checkAuth(req)) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { submissionId, personaSlug } = (await req.json()) as {
      submissionId: string;
      personaSlug?: string;
    };
    if (!submissionId) {
      return NextResponse.json({ error: "submissionId required" }, { status: 400 });
    }

    const outcome = await rewriteSubmission({ submissionId, personaSlug });
    return NextResponse.json({ ok: true, outcome });
  } catch (err: any) {
    return NextResponse.json({ error: err.message || String(err) }, { status: 500 });
  }
}
