import { NextResponse } from "next/server";
import { amiEvents, getAmiClient } from "@/lib/ami-manager";

interface AmiEventData {
  event?: string;
  actionid?: string;
  objectname?: unknown;
  aors?: unknown;
  contacts?: unknown;
  devicestate?: unknown;
  transport?: unknown;
  [key: string]: unknown;
}

// Recopila eventos AMI hasta recibir el evento final indicado
function collectByActionId(actionId: string, completeEvent: string): Promise<AmiEventData[]> {
  return new Promise<AmiEventData[]>((resolve) => {
    const buffer: AmiEventData[] = [];
    const handler = (evt: AmiEventData) => {
      if (evt?.actionid !== actionId) return;
      if (evt?.event === completeEvent) {
        amiEvents.removeListener("amiEvent", handler);
        resolve(buffer);
        return;
      }
      buffer.push(evt);
    };
    amiEvents.on("amiEvent", handler);
  });
}

interface AmiActionResponse {
  actionid?: string;
  [key: string]: unknown;
}

export async function GET(): Promise<NextResponse> {
  const ami = getAmiClient();

  // Ejecuta PJSIPShowEndpoints y espera todos los EndpointList
  const endpoints = await new Promise<AmiEventData[]>(async (resolve) => {
    ami.action({ action: "PJSIPShowEndpoints" }, async (err: Error | null, res: AmiActionResponse) => {
      if (err || !res?.actionid) return resolve([]);
      const list = await collectByActionId(String(res.actionid), "EndpointListComplete");
      resolve(list.filter((e) => e?.event === "EndpointList"));
    });
  });

  // Normaliza una versión pequeña y estable para el frontend
  const normalized = endpoints.map((e) => {
    const toStr = (val: unknown): string => {
      if (typeof val === 'string') return val;
      if (typeof val === 'number' || typeof val === 'boolean') return String(val);
      return '';
    };
    return {
      objectname: toStr(e.objectname),
      aors: toStr(e.aors),
      contacts: toStr(e.contacts),
      devicestate: toStr(e.devicestate) || "Unknown",
      transport: toStr(e.transport),
    };
  });

  // console.log(endpoints);

  return NextResponse.json({ endpoints: normalized });
}