import twilio from 'twilio';

type LicenseLike = { license_number: string; license_name: string; id: string };

function logDev(msg: string, payload?: unknown) {
  console.log(`[NOTIFY] ${msg}`, payload ?? '');
}

export class NotificationService {
  private static getTwilio() {
    const sid = process.env.TWILIO_ACCOUNT_SID;
    const token = process.env.TWILIO_AUTH_TOKEN;
    if (!sid || sid === 'your-sid' || !token || token === 'your-token') return null;
    return twilio(sid, token);
  }

  static async sendLicenseExpiryWarning(license: LicenseLike, daysRemaining: number): Promise<void> {
    const text = `WM-IMS: License ${license.license_number} (${license.license_name}) expires in ${daysRemaining} day(s). Renew soon.`;
    await this.sendToMdAndLegal(text, 'WARNING');
  }

  static async sendLicenseExpiredAlert(license: LicenseLike): Promise<void> {
    const text = `WM-IMS ALERT: License ${license.license_number} EXPIRED. Operational access revoked.`;
    await this.sendToMdAndLegal(text, 'EXPIRED');
  }

  static async sendRedAlert(message: string): Promise<void> {
    if (process.env.NOTIFY_MOCK === 'true' || process.env.NODE_ENV === 'development') {
      logDev('RED_ALERT', message);
      return;
    }
    const client = this.getTwilio();
    const from = process.env.TWILIO_PHONE_NUMBER;
    const md = process.env.MD_PHONE_NUMBER;
    const legal = process.env.LEGAL_OFFICER_PHONE;
    if (!client || !from) {
      logDev('RED_ALERT', message);
      return;
    }
    for (const to of [md, legal].filter(Boolean)) {
      try {
        await client.messages.create({ from, to: to!, body: message });
      } catch (e) {
        console.error('Twilio error', e);
      }
    }
  }

  private static async sendToMdAndLegal(
    body: string,
    _kind: 'WARNING' | 'EXPIRED'
  ): Promise<void> {
    if (process.env.NOTIFY_MOCK === 'true' || process.env.NODE_ENV === 'development') {
      logDev(_kind, body);
      return;
    }
    const client = this.getTwilio();
    const from = process.env.TWILIO_PHONE_NUMBER;
    const md = process.env.MD_PHONE_NUMBER;
    const legal = process.env.LEGAL_OFFICER_PHONE;
    if (!client || !from) {
      logDev(_kind, body);
      return;
    }
    for (const to of [md, legal].filter(Boolean)) {
      try {
        await client.messages.create({ from, to: to!, body });
      } catch (e) {
        console.error('Twilio error', e);
      }
    }
  }
}
