import { logger } from '../config/logger';

export class WhatsappService {
  private static phoneNumberId = process.env.META_WHATSAPP_PHONE_NUMBER_ID || '105574302636254';
  private static accessToken = process.env.META_WHATSAPP_ACCESS_TOKEN || 'EAA...';

  /**
   * Send Template Message via Meta WhatsApp Cloud API
   */
  static async sendTemplateMessage(recipientPhone: string, templateName: string, parameters: Array<{ type: string; text: string }>): Promise<boolean> {
    const formattedPhone = recipientPhone.replace(/\D/g, ''); // Ensure digits only (e.g. 919876543210)
    const isMock = this.accessToken === 'EAA...' || !process.env.META_WHATSAPP_ACCESS_TOKEN;

    if (isMock) {
      logger.info(`[WhatsAppService] [MOCK SEND] Sent template '${templateName}' to ${formattedPhone} with parameters:`, parameters);
      return true;
    }

    try {
      const response = await fetch(`https://graph.facebook.com/v17.0/${this.phoneNumberId}/messages`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${this.accessToken}`,
        },
        body: JSON.stringify({
          messaging_product: 'whatsapp',
          to: formattedPhone,
          type: 'template',
          template: {
            name: templateName,
            language: { code: 'en_US' },
            components: [
              {
                type: 'body',
                parameters: parameters,
              },
            ],
          },
        }),
      });

      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error?.message || 'Meta API request failed');
      }

      logger.info(`[WhatsAppService] Message successfully dispatched. ID: ${data.messages?.[0]?.id}`);
      return true;
    } catch (err: any) {
      logger.error(`[WhatsAppService] Meta API Error: ${err.message}`);
      return false;
    }
  }

  // Predefined triggers
  static async sendOrderConfirmation(phone: string, customerName: string, orderNumber: string) {
    return this.sendTemplateMessage(phone, 'order_confirmation', [
      { type: 'text', text: customerName },
      { type: 'text', text: orderNumber },
    ]);
  }

  static async sendShippingUpdate(phone: string, orderNumber: string, awb: string, courier: string) {
    return this.sendTemplateMessage(phone, 'shipping_update', [
      { type: 'text', text: orderNumber },
      { type: 'text', text: awb },
      { type: 'text', text: courier },
    ]);
  }

  static async sendOtp(phone: string, code: string) {
    return this.sendTemplateMessage(phone, 'otp_notification', [
      { type: 'text', text: code },
    ]);
  }
}
