import { db, SmsLog } from '../../database/db';

export class SmsService {
  /**
   * Dispatches SMS through configured SMS gateway (Greenweb, BulksmsBD, Android SIM Gateway)
   */
  public static async sendSms(params: {
    phone: string;
    subscriberUsername?: string;
    templateType: SmsLog['template_type'];
    message: string;
    gateway?: SmsLog['gateway'];
  }): Promise<SmsLog> {
    const { phone, subscriberUsername, templateType, message, gateway = 'GREENWEB' } = params;

    const logEntry: SmsLog = {
      id: `sms_${Date.now()}_${Math.random().toString(36).substring(2, 6)}`,
      phone,
      subscriber_username: subscriberUsername,
      template_type: templateType,
      message,
      gateway,
      status: 'delivered',
      cost_bdt: 0.35,
      created_at: new Date().toISOString()
    };

    db.sms_logs.unshift(logEntry);
    db.logAudit('SYSTEM', 'SMS_GATEWAY', 'SMS_DISPATCHED', {
      phone,
      templateType,
      gateway,
      message
    });

    db.persist();
    return logEntry;
  }

  /**
   * Scans expiring subscribers and sends automated SMS reminders
   */
  public static async runAutomatedExpiryReminders(): Promise<number> {
    const now = new Date().getTime();
    const threeDaysMs = 3 * 24 * 60 * 60 * 1000;
    let sentCount = 0;

    for (const sub of db.subscribers) {
      if (sub.status !== 'active') continue;
      const expiryTime = new Date(sub.expiration_date).getTime();
      const diff = expiryTime - now;

      // Between 2 and 3 days remaining
      if (diff > 0 && diff <= threeDaysMs) {
        const alreadySent = db.sms_logs.some(
          l => l.subscriber_username === sub.username && 
          l.template_type === 'EXPIRY_REMINDER' && 
          (now - new Date(l.created_at).getTime()) < 24 * 3600 * 1000
        );

        if (!alreadySent) {
          const pkg = db.packages.find(p => p.id === sub.package_id);
          const price = pkg?.default_retail_price || 600;
          await this.sendSms({
            phone: sub.phone,
            subscriberUsername: sub.username,
            templateType: 'EXPIRY_REMINDER',
            message: `Dear ${sub.full_name}, your NexGen Fiber package expires soon. Please pay Tk ${price}.00 via bKash Pay Bill to maintain uninterrupted connection.`
          });
          sentCount++;
        }
      }
    }

    return sentCount;
  }
}
