// SMS Service for OTP delivery
import { createTransporter } from './email-service';

interface SMSProvider {
  sendSMS(to: string, message: string): Promise<boolean>;
}

// MSG91 SMS Provider (Indian service)
class MSG91SMSProvider implements SMSProvider {
  private authKey: string;
  private templateId: string;

  constructor() {
    this.authKey = process.env.MSG91_AUTH_KEY || '462769AcJdGeJIRl68933254P1';
    this.templateId = process.env.MSG91_TEMPLATE_ID || '6894776284c42857d572d99b';

    console.log('🔍 MSG91 Environment check:');
    console.log('   AUTH_KEY from env:', process.env.MSG91_AUTH_KEY ? 'FOUND' : 'NOT FOUND');
    console.log('   TEMPLATE_ID from env:', process.env.MSG91_TEMPLATE_ID ? 'FOUND' : 'NOT FOUND');
    console.log('   Using AUTH_KEY:', this.authKey.substring(0, 10) + '...');
    console.log('   Using TEMPLATE_ID:', this.templateId);

    if (this.authKey && this.templateId) {
      console.log('✅ MSG91 SMS service initialized with credentials');
    } else {
      console.log('⚠️  MSG91 credentials not configured properly');
    }
  }

  // Format phone number to ensure proper country code
  private formatPhoneNumber(phoneNumber: string): string {
    // Remove all non-digits
    const cleanNumber = phoneNumber.replace(/\D/g, '');
    
    // If starts with country code (91), use as is
    if (cleanNumber.startsWith('91') && cleanNumber.length === 12) {
      return cleanNumber;
    }
    
    // If 10 digits, add Indian country code
    if (cleanNumber.length === 10) {
      return '91' + cleanNumber;
    }
    
    // Return as is for other formats
    return cleanNumber;
  }

  async sendSMS(to: string, message: string): Promise<boolean> {
    if (!this.authKey || !this.templateId) {
      console.log(`📱 SMS (Console Mode - MSG91) to ${to}: ${message}`);
      return true;
    }

    try {
      // Extract OTP from message
      const otpMatch = message.match(/\d{6}/);
      const otp = otpMatch ? otpMatch[0] : '123456';

      const fetch = (await import('node-fetch')).default as any;
      
      // Try Flow API first (recommended for DLT templates)
      const response = await fetch('https://api.msg91.com/api/v5/flow/', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'authkey': this.authKey
        },
        body: JSON.stringify({
          template_id: this.templateId, // DLT approved template ID
          recipients: [
            {
              mobiles: this.formatPhoneNumber(to), // Ensure proper format with country code
              var: otp   // Standard MSG91 variable format
            }
          ]
        })
      });

      const result = await response.json() as any;
      
      if (response.ok && result.type === 'success') {
        console.log(`✅ MSG91 SMS sent successfully to ${to}`);
        return true;
      } else {
        console.error('❌ MSG91 SMS failed:', result);
        return false;
      }
    } catch (error) {
      console.error('❌ Failed to send MSG91 SMS:', error);
      return false;
    }
  }
}

// Twilio SMS Provider
class TwilioSMSProvider implements SMSProvider {
  private client: any;
  private fromNumber: string;

  constructor() {
    const accountSid = process.env.TWILIO_ACCOUNT_SID;
    const authToken = process.env.TWILIO_AUTH_TOKEN;
    this.fromNumber = process.env.TWILIO_PHONE_NUMBER || '';

    if (accountSid && authToken && this.fromNumber) {
      // Only initialize Twilio if credentials are available
      try {
        const twilio = require('twilio');
        this.client = twilio(accountSid, authToken);
        console.log('✅ Twilio SMS service initialized');
      } catch (error) {
        console.log('⚠️  Twilio not available, falling back to console logging');
        this.client = null;
      }
    } else {
      console.log('⚠️  Twilio credentials not configured, using console logging');
      this.client = null;
    }
  }

  async sendSMS(to: string, message: string): Promise<boolean> {
    if (!this.client) {
      console.log(`📱 SMS (Console Mode) to ${to}: ${message}`);
      return true;
    }

    try {
      const result = await this.client.messages.create({
        body: message,
        from: this.fromNumber,
        to: to
      });
      console.log(`✅ SMS sent successfully to ${to}, SID: ${result.sid}`);
      return true;
    } catch (error) {
      console.error('❌ Failed to send SMS:', error);
      return false;
    }
  }
}

// Email OTP Provider (fallback)
class EmailOTPProvider implements SMSProvider {
  async sendSMS(to: string, message: string): Promise<boolean> {
    try {
      const transporter = createTransporter();
      if (!transporter) {
        console.log(`📧 Email OTP (Console Mode) to ${to}: ${message}`);
        return true;
      }

      await transporter.sendMail({
        from: process.env.EMAIL_FROM || 'noreply@myymotto.com',
        to: to,
        subject: 'MyyMotto - Your Verification Code',
        html: `
          <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
            <h2 style="color: #ff6b35;">MyyMotto Verification</h2>
            <p>Your verification code is:</p>
            <div style="background: #f5f5f5; padding: 20px; text-align: center; font-size: 24px; font-weight: bold; letter-spacing: 3px; border-radius: 8px; margin: 20px 0;">
              ${message.match(/\d{6}/)?.[0] || 'ERROR'}
            </div>
            <p style="color: #666;">This code will expire in 5 minutes.</p>
            <p style="color: #666;">If you didn't request this code, please ignore this email.</p>
          </div>
        `
      });
      console.log(`✅ Email OTP sent successfully to ${to}`);
      return true;
    } catch (error) {
      console.error('❌ Failed to send email OTP:', error);
      console.log(`📧 Email OTP (Console Mode) to ${to}: ${message}`);
      return true;
    }
  }
}

// SMS Service Manager
class SMSService {
  private provider: SMSProvider;

  constructor() {
    // Always use MSG91 with configured credentials (fallback to hardcoded for production)
    this.provider = new MSG91SMSProvider();
    console.log('📱 Initializing MSG91 SMS service (Indian provider with DLT approval)');
    
    // Backup provider check
    if (!process.env.MSG91_AUTH_KEY || !process.env.MSG91_TEMPLATE_ID) {
      console.log('📱 Using fallback MSG91 credentials (production ready)');
    }
  }

  async sendOTP(identifier: string, otp: string): Promise<boolean> {
    const isEmail = identifier.includes('@');
    const isMobile = /^\+?[\d\s-()]+$/.test(identifier.trim());

    if (isEmail) {
      // Always use email for email addresses
      const emailProvider = new EmailOTPProvider();
      return await emailProvider.sendSMS(identifier, `Your MyyMotto verification code is: ${otp}`);
    } else if (isMobile) {
      // Use configured SMS provider for mobile numbers
      return await this.provider.sendSMS(identifier, `Your MyyMotto verification code is: ${otp}. Valid for 5 minutes.`);
    } else {
      console.error('❌ Invalid identifier format:', identifier);
      return false;
    }
  }
}

export const smsService = new SMSService();