/**
 * POST /api/page-studio/optimize-cta — AI-powered CTA optimization.
 * Analyzes brand conversion data and recommends optimal CTA config.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { optimizeCTA } from "@/lib/services/cta-optimizer";

export const dynamic = "force-dynamic";
export const maxDuration = 30;

export async function POST(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const body = await req.json().catch(() => null);
  const brandId = body?.brandId as string | undefined;
  const currentCTA = body?.currentCTA as string | undefined;

  if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

  const brand = await prisma.brand.findUnique({
    where: { id: brandId },
    include: { organization: { include: { memberships: true } } },
  });
  if (!brand) return NextResponse.json({ error: "Brand not found" }, { status: 404 });
  if (!brand.organization.memberships.some((m) => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  try {
    const recommendation = await optimizeCTA(brandId, currentCTA || "Get Started");
    return NextResponse.json(recommendation);
  } catch (err) {
    return NextResponse.json(
      { error: err instanceof Error ? err.message : "CTA optimization failed" },
      { status: 500 },
    );
  }
}
