import { invalidateProjects, projectRef } from "@/lib/projects";
import { pieceHrefOfProject } from "@/lib/pieces/article";
import { refuseCaller } from "@/lib/report/caller";
import { StaleToken, StructureRefused } from "@/lib/report/manifest.mjs";
import { PromoteStale, promoteTake } from "@/lib/report/takeEdit.mjs";
import { isTakeId } from "@/lib/report/takes.mjs";
export const dynamic = "force-dynamic";
// "MAKE THIS THE CUT" (walk a take). POST { project, take, anyway? }
//
// The take's manifest -- the project's as it is now with the take's patch
// applied, walked edits and all -- over the project's, through the manifest
// writer (replaceManifest: ONE auto snapshot `auto-before-promote-take`, so
// the Cut tab's "Undo last edit" takes the whole promotion back) inside the
// edit-notes guard; then the take's group's pick in takes/verdicts.json.
// The CLI twin is `umtool take
--id --promote [--anyway]`.
//
// Not "Use this take" (/api/report/takes/pick), which copies the manifest a
// take was RENDERED from: this applies its patch now, so a draft promotes.
//
// 409 `{ stale: true }` when the take replaces the timeline and the project's
// manifest changed since the take was made, until `anyway`.
export async function POST(request: Request) {
const refused = refuseCaller(request, "/api/report/takes/promote");
if (refused) return refused;
const body = (await request.json().catch(() => null)) as { project?: unknown; take?: unknown; anyway?: unknown } | null;
if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400 });
if (!isTakeId(body.take)) return Response.json({ error: "take must be a take id" }, { status: 400 });
const project = await projectRef(String(body.project ?? ""));
if (!project) return Response.json({ error: "no such project" }, { status: 404 });
try {
const r = await promoteTake(project, body.take, { anyway: body.anyway === true });
invalidateProjects();
const historyHref = await pieceHrefOfProject(project.id, { tab: "history" });
return Response.json({ ok: true, ...r, historyHref }, { headers: { "cache-control": "no-store" } });
} catch (e) {
if (e instanceof PromoteStale) return Response.json({ error: e.message, stale: true }, { status: 409 });
if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 });
if (e instanceof StructureRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400 });
const message = e instanceof Error ? e.message : String(e);
return Response.json({ error: message }, { status: /^no take /.test(message) ? 404 : 400 });
}
}