type WhatsAppTemplateOptions = {
  templateName: string;
  languageCode?: string;
  to?: string;
  components?: unknown[];
};

type WhatsAppTextOptions = {
  body: string;
  to?: string;
};

function getWhatsAppConfig() {
  const accessToken = process.env.WHATSAPP_ACCESS_TOKEN;
  const phoneNumberId = process.env.WHATSAPP_PHONE_NUMBER_ID;
  const ownerWhatsApp = process.env.PELCY_OWNER_WHATSAPP;
  const graphVersion =
    process.env.WHATSAPP_GRAPH_API_VERSION || "v26.0";

  if (!accessToken) {
    throw new Error("WHATSAPP_ACCESS_TOKEN is not configured");
  }

  if (!phoneNumberId) {
    throw new Error("WHATSAPP_PHONE_NUMBER_ID is not configured");
  }

  return {
    accessToken,
    phoneNumberId,
    ownerWhatsApp,
    graphVersion,
  };
}

async function sendWhatsAppRequest(payload: Record<string, unknown>) {
  const {
    accessToken,
    phoneNumberId,
    graphVersion,
  } = getWhatsAppConfig();

  const response = await fetch(
    `https://graph.facebook.com/${graphVersion}/${phoneNumberId}/messages`,
    {
      method: "POST",
      headers: {
        Authorization: `Bearer ${accessToken}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify(payload),
    }
  );

  const result = await response.json();

  if (!response.ok) {
    const message =
      (result as any)?.error?.message ||
      "Failed to send WhatsApp message";

    throw new Error(message);
  }

  return {
    messageId: (result as any)?.messages?.[0]?.id ?? null,
  };
}

export async function sendWhatsAppTemplate(
  options: WhatsAppTemplateOptions
) {
  const { ownerWhatsApp } = getWhatsAppConfig();

  const recipient = options.to || ownerWhatsApp;

  if (!recipient) {
    throw new Error("PELCY_OWNER_WHATSAPP is not configured");
  }

  const template: Record<string, unknown> = {
    name: options.templateName,
    language: {
      code: options.languageCode || "en_US",
    },
  };

  if (options.components && options.components.length > 0) {
    template.components = options.components;
  }

  return sendWhatsAppRequest({
    messaging_product: "whatsapp",
    recipient_type: "individual",
    to: recipient,
    type: "template",
    template,
  });
}

export async function sendWhatsAppText(
  options: WhatsAppTextOptions
) {
  const { ownerWhatsApp } = getWhatsAppConfig();

  const recipient = options.to || ownerWhatsApp;

  if (!recipient) {
    throw new Error("PELCY_OWNER_WHATSAPP is not configured");
  }

  return sendWhatsAppRequest({
    messaging_product: "whatsapp",
    recipient_type: "individual",
    to: recipient,
    type: "text",
    text: {
      preview_url: false,
      body: options.body,
    },
  });
}