import axios from "axios";
import { config } from "./config.js";

function ariAuthHeader(): string {
  const creds = Buffer.from(`${config.ariUser}:${config.ariPass}`).toString("base64");
  return `Basic ${creds}`;
}

export async function originateAriCall(callId: string): Promise<{
  ok: boolean;
  skipped: boolean;
  status?: number;
  body?: unknown;
  reason?: string;
}> {
  if (!config.enableAriOriginate) {
    return { ok: false, skipped: true, reason: "ENABLE_ARI_ORIGINATE=0" };
  }
  if (config.ariUser === "" || config.ariPass === "") {
    return { ok: false, skipped: true, reason: "ARI credentials missing" };
  }

  const endpoint = config.ariEndpointTemplate.replace("{EXT}", config.freepbxTargetExt);
  const channelId = `wa-${callId}`.slice(0, 80);
  const url = `${config.ariBaseUrl}/channels`;

  try {
    const response = await axios.post(
      url,
      null,
      {
        timeout: 5000,
        params: {
          endpoint,
          app: config.ariApp,
          callerId: "WhatsApp <1000>",
          timeout: 30,
          channelId,
        },
        headers: {
          Authorization: ariAuthHeader(),
        },
        validateStatus: () => true,
      },
    );

    return {
      ok: response.status >= 200 && response.status < 300,
      skipped: false,
      status: response.status,
      body: response.data,
    };
  } catch (error) {
    if (axios.isAxiosError(error)) {
      return {
        ok: false,
        skipped: false,
        status: error.response?.status,
        body: error.response?.data,
        reason: error.message,
      };
    }
    return { ok: false, skipped: false, reason: String(error) };
  }
}
