/* eslint-disable camelcase */

import axios from 'axios';
import config from '../config/config';

interface WhatsAppPayload {
  messaging_product: string;
  to: string;
  type: string;
  template: {
    name: string;
    language: { code: string };
    components: Component[];
  };
}

type NamedVars = Record<string, string>;
type PositionalVars = string[];

interface ComponentParam {
  type: 'text';
  text: string;
  parameter_name?: string;
}

interface Component {
  type: 'BODY' | 'HEADER' | 'FOOTER' | 'BUTTON';
  parameters: ComponentParam[];
  sub_type?: string;
  index?: number;
}

export function buildComponents(
  variables: NamedVars | PositionalVars,
  isNamed: boolean = false,
): Component[] {
  const isArray = Array.isArray(variables);
  const isObject = !!variables && typeof variables === 'object' && !isArray;

  // If caller forgot to set isNamedParams but passed an object, treat it as named.
  if (isNamed || isObject)
    return [
      {
        type: 'BODY',
        parameters: Object.entries(variables as NamedVars).map(
          ([key, val]) => ({
            type: 'text',
            text: String(val),
            parameter_name: key,
          }),
        ),
      },
    ];

  // Positional variables
  const positional: PositionalVars = isArray
    ? (variables as PositionalVars)
    : [String(variables)];

  return [
    {
      type: 'BODY',
      parameters: positional.map((val) => ({
        type: 'text',
        text: String(val),
      })),
    },
  ];
}

export function buildAuthenticationTemplateComponents(
  otpCode: string,
  //   codeExpirationMinutes: number = 15,
  //   otpButtonType: 'COPY_CODE' | 'ONE_TAP' = 'COPY_CODE',
): Component[] {
  return [
    {
      type: 'BODY',
      parameters: [{ type: 'text', text: otpCode }],
    },
    {
      type: 'FOOTER',
      parameters: [],
    },
    {
      type: 'BUTTON',
      sub_type: 'url', // must be 'url'
      index: 0,
      parameters: [{ type: 'text', text: otpCode }],
      //   otp_type: otpButtonType,
    },
  ];
}

export function buildWhatsAppPayload(
  to: string,
  templateName: string,
  variables?: NamedVars | PositionalVars,
  isNamedParams = false,
  languageCode = 'en',
  isAuthenticationTemplate = false,
  //   codeExpirationMinutes = 15,
  //   otpButtonType: 'COPY_CODE' | 'ONE_TAP' = 'COPY_CODE',
) {
  if (isAuthenticationTemplate) {
    const otp = Array.isArray(variables)
      ? variables[0]
      : typeof variables === 'string'
        ? variables
        : variables && typeof variables === 'object'
          ? Object.values(variables as NamedVars)[0]
          : '';

    return {
      messaging_product: 'whatsapp',
      to,
      type: 'template',
      template: {
        name: templateName,
        language: { code: languageCode },
        components: buildAuthenticationTemplateComponents(String(otp ?? '')),
      },
    };
  } else {
    const components = variables
      ? buildComponents(variables, isNamedParams)
      : [];
    return {
      messaging_product: 'whatsapp',
      to,
      type: 'template',
      template: {
        name: templateName,
        language: { code: languageCode },
        components,
      },
    };
  }
}

export async function sendMessage(
  payload: WhatsAppPayload,
  accessToken: string,
  phoneNumberId?: string,
) {
  try {
    const response = await axios.post(
      `${config.metaApiPath}/${phoneNumberId ?? config.whatsappTemplate.phoneNumberId}/messages`,
      payload,
      {
        headers: {
          Authorization: `Bearer ${accessToken ?? config.whatsappTemplate.accessToken}`,
          'Content-Type': 'application/json',
        },
      },
    );
    console.log('🚀 ~ sendMessage ~ response:', response.data);
    return true;
  } catch (error) {
    console.error(
      'Failed to send WhatsApp message:',
      error.response ? error.response.data : error.message,
    );
    return false;
  }
}

export async function sendWhatsAppTemplateMessage(
  toNumber: string,
  templateName: string,
  variables: NamedVars | PositionalVars = [],
  isNamedParams: boolean = false,
  languageCode: string = 'en',
  isAuthenticationTemplate: boolean = false,
  accessToken: string = '',
  phoneNumberId: string = '',
): Promise<boolean> {
  const payload = buildWhatsAppPayload(
    toNumber,
    templateName,
    variables,
    isNamedParams,
    languageCode,
    isAuthenticationTemplate,
  );

  accessToken =
    accessToken && accessToken.trim() !== ''
      ? accessToken
      : config.whatsappTemplate?.accessToken;

  phoneNumberId =
    phoneNumberId && phoneNumberId.trim() !== ''
      ? phoneNumberId
      : config.whatsappTemplate?.phoneNumberId;

  // Send the message using your sendMessage function
  const success = await sendMessage(payload, accessToken, phoneNumberId);

  return success;
}
