import { NextResponse } from "next/server";
import { executeAmiAction, getAmiClient, isAmiConnected } from "@/lib/ami-manager";

export const dynamic = "force-dynamic"; // asegurar ejecución en runtime

export async function POST(request: Request) {
  try {
    // Asegurar cliente inicializado
    getAmiClient();

    const body = await request.json() as { action?: string; params?: Record<string, string | number | boolean> };
    const { action, params } = body;

    if (!action) {
      return NextResponse.json(
        { success: false, error: "Falta 'action' en el cuerpo" },
        { status: 400 },
      );
    }

    if (!isAmiConnected()) {
      return NextResponse.json(
        { success: false, error: "AMI no conectado" },
        { status: 503 },
      );
    }

    // Normalizar acciones comunes
    // Originate: requiere channel, context/exten o application, priority
    // Hangup: requiere channel
    // Redirect: requiere channel, context, exten, priority
    const result = await executeAmiAction(action, params ?? {});
    return NextResponse.json(result, { status: result.success ? 200 : 500 });
  } catch (error) {
    console.error("[AMI Action] Error:", error);
    return NextResponse.json(
      { success: false, error: "Error interno ejecutando acción AMI" },
      { status: 500 },
    );
  }
}