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

export async function acceptMetaCall(callId: string): Promise<{
  ok: boolean;
  skipped: boolean;
  status?: number;
  body?: unknown;
  reason?: string;
}> {
  if (config.metaToken === "") {
    return { ok: false, skipped: true, reason: "META_TOKEN missing" };
  }
  if (config.metaCallAcceptUrlTemplate === "") {
    return { ok: false, skipped: true, reason: "META_CALL_ACCEPT_URL_TEMPLATE missing" };
  }

  const url = config.metaCallAcceptUrlTemplate.replace("{CALL_ID}", encodeURIComponent(callId));
  try {
    const response = await axios.post(
      url,
      config.phoneNumberId !== "" ? { phone_number_id: config.phoneNumberId } : {},
      {
        timeout: 5000,
        headers: {
          Authorization: `Bearer ${config.metaToken}`,
          "Content-Type": "application/json",
        },
        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) };
  }
}
