import { NextResponse } from "next/server";
import type { BrandProfile, PostSequenceItem, Project } from "@/types/workflow";
import { buildAllBrandContextPreviews } from "@/lib/context/context-refresh-server";

export async function POST(request: Request) {
  try {
    const body = (await request.json()) as {
      projectId: string;
      project: Project;
      brand: BrandProfile;
      posts: PostSequenceItem[];
      campaignName?: string;
    };

    if (!body.projectId || !body.project || !body.brand || !body.posts?.length) {
      return NextResponse.json({ error: "Missing project, brand, or posts." }, { status: 400 });
    }

    const refreshed = await buildAllBrandContextPreviews(
      body.brand,
      body.project,
      body.posts,
      body.campaignName,
    );

    return NextResponse.json({ posts: refreshed });
  } catch (err) {
    const message = err instanceof Error ? err.message : "Refresh failed";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
