import { Injectable, Logger } from '@nestjs/common';

/**
 * WhatsApp service — sends messages via Evolution API.
 *
 * Set env vars to enable:
 *   WHATSAPP_ENABLED=true
 *   EVOLUTION_API_URL=http://localhost:8080
 *   EVOLUTION_API_KEY=your-strong-key
 *   EVOLUTION_INSTANCE=qrs-notifier
 *
 * When WHATSAPP_ENABLED is not "true", every send() call is a no-op
 * (logs and returns { success: false, error: 'WhatsApp disabled' }).
 *
 * This lets us deploy the code now and enable WhatsApp later when
 * the Evolution API Docker + business SIM are ready.
 */
@Injectable()
export class WhatsappService {
  private readonly logger = new Logger(WhatsappService.name);

  private readonly enabled: boolean;
  private readonly baseUrl: string;
  private readonly apiKey: string;
  private readonly instance: string;

  constructor() {
    this.enabled = String(process.env.WHATSAPP_ENABLED).toLowerCase() === 'true';
    this.baseUrl = process.env.EVOLUTION_API_URL || 'http://localhost:8080';
    this.apiKey = process.env.EVOLUTION_API_KEY || '';
    this.instance = process.env.EVOLUTION_INSTANCE || 'qrs-notifier';

    if (this.enabled) {
      this.logger.log(
        `WhatsApp ENABLED — Evolution API @ ${this.baseUrl} (instance: ${this.instance})`,
      );
    } else {
      this.logger.log('WhatsApp DISABLED (set WHATSAPP_ENABLED=true to activate)');
    }
  }

  /**
   * Send a plain-text WhatsApp message.
   * @param phoneNumber E.164 format (e.g. '+971501234567'). Must include country code.
   * @param message Plain text (max ~4096 chars). Use \n for line breaks.
   */
  async sendText(
    phoneNumber: string,
    message: string,
  ): Promise<{ success: boolean; error?: string; messageId?: string }> {
    if (!this.enabled) {
      return { success: false, error: 'WhatsApp disabled' };
    }

    if (!phoneNumber || !phoneNumber.trim()) {
      return { success: false, error: 'No phone number' };
    }

    const cleanNumber = phoneNumber.replace(/[^\d+]/g, ''); // strip spaces, dashes

    try {
      const url = `${this.baseUrl}/message/sendText/${this.instance}`;
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          apikey: this.apiKey,
        },
        body: JSON.stringify({
          number: cleanNumber,
          text: message,
        }),
      });

      if (!response.ok) {
        const errText = await response.text();
        this.logger.warn(
          `WhatsApp failed for ${cleanNumber}: HTTP ${response.status} — ${errText}`,
        );
        return { success: false, error: `HTTP ${response.status}: ${errText}` };
      }

      const data = (await response.json()) as any;
      const messageId = data?.key?.id || data?.id || undefined;
      this.logger.log(`WhatsApp sent to ${cleanNumber} (msgId: ${messageId})`);
      return { success: true, messageId };
    } catch (err: any) {
      this.logger.warn(`WhatsApp error for ${cleanNumber}: ${err.message}`);
      return { success: false, error: err.message };
    }
  }

  /**
   * Convenience wrapper — accepts an array of recipients, sends to each.
   * Returns counts of successes/failures.
   */
  async sendToMany(
    recipients: Array<{ phone_number?: string | null; id?: number }>,
    message: string,
  ): Promise<{ sent: number; failed: number }> {
    let sent = 0;
    let failed = 0;

    for (const r of recipients) {
      if (!r.phone_number) {
        failed++;
        continue;
      }
      const result = await this.sendText(r.phone_number, message);
      if (result.success) sent++;
      else failed++;
    }

    return { sent, failed };
  }
}