require('dotenv').config();
const twilio = require('twilio');

// Initialize Twilio using API Key
// Account SID is still required for API Key auth
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const apiKey = process.env.TWILIO_API_KEY_SID;
const apiSecret = process.env.TWILIO_API_KEY_SECRET;

const client = twilio(apiKey, apiSecret, { accountSid });
const fromNumber = process.env.TWILIO_WHATSAPP_FROM || 'whatsapp:+14155238886'; // Fallback to sandbox if not set

class WhatsAppService {
    async sendWhatsApp(to, body) {
        if (!to) {
            console.error('[WhatsAppService] Missing destination phone number');
            return { success: false, error: 'Missing phone number' };
        }
        
        // Ensure "whatsapp:" prefix
        const toFormatted = to.startsWith('whatsapp:') ? to : `whatsapp:${to.startsWith('+') ? to : '+' + to}`;

        try {
            const message = await client.messages.create({
                body: body,
                from: fromNumber,
                to: toFormatted
            });
            console.log(`[WhatsAppService] Message sent to ${toFormatted}. SID: ${message.sid}`);
            return { success: true, sid: message.sid };
        } catch (error) {
            console.error(`[WhatsAppService] Failed to send message to ${toFormatted}:`, error.message);
            return { success: false, error: error.message };
        }
    }

    async sendTokenConfirmation(phone, tokenNumber, clinicName, slotTime, fee) {
        const message = `🏥 *CuraFlow Token Confirmed*\n\n🔢 Token: ${tokenNumber}\n🏨 Clinic: ${clinicName}\n🕐 Slot: ${slotTime}\n💰 Fee: ₹${fee}\n\nPlease arrive 10 mins early.`;
        return this.sendWhatsApp(phone, message);
    }

    async sendQueueUpdate(phone, clinicName, position, estimatedTime) {
        const message = `📋 *Queue Update*\n\nYou are #${position} in line at ${clinicName}.\n⏱ Estimated wait: ~${estimatedTime} mins`;
        return this.sendWhatsApp(phone, message);
    }

    async sendRescheduleOffer(phone, clinicName, oldTime, newTime) {
        const message = `🔔 *Slot Available!*\n\nA slot opened at ${clinicName} for ${newTime}!\nYour current: ${oldTime}\n\nReply:\n1. Yes, move me!\n2. No, keep my current time.`;
        return this.sendWhatsApp(phone, message);
    }

    async sendCancellationConfirmation(phone, clinicName, slotTime) {
        const message = `✅ *Booking Cancelled*\n\nYour token at ${clinicName} for ${slotTime} has been cancelled.`;
        return this.sendWhatsApp(phone, message);
    }
}

module.exports = new WhatsAppService();
