/**
 * POST /api/ai-avatar/execute
 * ----------------------------
 * Runs an execution hook when the user clicks an action button
 * in the AI Avatar panel.
 *
 * Request body:
 *   {
 *     actionType:  string              — "create_task", "generate_report", etc.
 *     brandId:     string              — the selected brand
 *     currentPage: string              — the page the user is on
 *     payload:     Record<string,string> — action-specific data
 *   }
 *
 * Response:
 *   { ok: boolean, message: string, data?: Record<string,unknown> }
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { buildAvatarContext } from "@/lib/ai-avatar/context-builder";
import { executeHook } from "@/lib/ai-avatar/execution-hooks";

export const dynamic = "force-dynamic";

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

  // ── Parse request ──
  const body = await req.json();
  const { actionType, brandId, currentPage, payload } = body as {
    actionType: string;
    brandId: string;
    currentPage: string;
    payload: Record<string, string>;
  };

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

  // ── Build context ──
  const ctx = await buildAvatarContext(brandId, currentPage || "/", user.id);
  if (!ctx) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  // ── Execute the hook ──
  const result = await executeHook(actionType, ctx, payload ?? {});

  return NextResponse.json(result);
}
