import axios from 'axios';
import { EmailLang } from '../utils/emailTemplates';

type AppointmentMessageKind = 'reminder' | 'confirmation' | 'cancellation' | 'rescheduled' | 'completed';

export class WhatsAppService {
    private accountSid = process.env.TWILIO_ACCOUNT_SID || '';
    private authToken = process.env.TWILIO_AUTH_TOKEN || '';
    private fromNumber = process.env.TWILIO_WHATSAPP_FROM || ''; // ex: whatsapp:+14155238886

    isEnabled(): boolean {
        return Boolean(this.accountSid && this.authToken && this.fromNumber);
    }

    async sendAppointmentReminder(
        to: string,
        name: string,
        date: string,
        doctorName: string,
        lang: EmailLang = 'en'
    ): Promise<boolean> {
        const text = this.getAppointmentText('reminder', { name, date, doctorName, lang });
        return this.sendMessage(to, text);
    }

    async sendAppointmentConfirmation(
        to: string,
        name: string,
        date: string,
        doctorName: string,
        lang: EmailLang = 'en'
    ): Promise<boolean> {
        const text = this.getAppointmentText('confirmation', { name, date, doctorName, lang });
        return this.sendMessage(to, text);
    }

    async sendAppointmentCancellation(
        to: string,
        name: string,
        date: string,
        doctorName: string,
        lang: EmailLang = 'en'
    ): Promise<boolean> {
        const text = this.getAppointmentText('cancellation', { name, date, doctorName, lang });
        return this.sendMessage(to, text);
    }

    async sendAppointmentRescheduled(
        to: string,
        name: string,
        oldDate: string,
        newDate: string,
        doctorName: string,
        lang: EmailLang = 'en'
    ): Promise<boolean> {
        const text = this.getAppointmentText('rescheduled', { name, oldDate, newDate, doctorName, lang });
        return this.sendMessage(to, text);
    }

    async sendAppointmentCompleted(
        to: string,
        name: string,
        date: string,
        doctorName: string,
        lang: EmailLang = 'en'
    ): Promise<boolean> {
        const text = this.getAppointmentText('completed', { name, date, doctorName, lang });
        return this.sendMessage(to, text);
    }

    private async sendMessage(to: string, body: string): Promise<boolean> {
        if (!this.isEnabled()) {
            console.warn('[WhatsAppService] Twilio WhatsApp not configured. Skipping message send.');
            return false;
        }

        const toNumber = this.normalizeWhatsAppAddress(to); // force override for testing
        if (!toNumber) {
            console.warn('[WhatsAppService] Invalid recipient phone number for WhatsApp');
            return false;
        }

        const url = `https://api.twilio.com/2010-04-01/Accounts/${this.accountSid}/Messages.json`;
        const payload = new URLSearchParams({
            From: this.normalizeWhatsAppAddress(this.fromNumber) || this.fromNumber,
            To: toNumber,
            Body: body,
        });

        try {
            const response = await axios.post(url, payload.toString(), {
                auth: {
                    username: this.accountSid,
                    password: this.authToken,
                },
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
            });

            console.log(`[WhatsAppService] ✓ Message sent to ${toNumber} (SID: ${response.data?.sid || 'n/a'})`);
            return true;
        } catch (error: any) {
            const detail = error?.response?.data || error?.message || error;
            console.error(`[WhatsAppService] Failed sending WhatsApp to ${toNumber}:`, detail);
            return false;
        }
    }

    private normalizeWhatsAppAddress(value?: string): string | null {
        if (!value) return null;

        const trimmed = value.trim();
        if (!trimmed) return null;

        if (trimmed.startsWith('whatsapp:')) {
            return trimmed;
        }

        return `whatsapp:${trimmed}`;
    }

    private getAppointmentText(
        kind: AppointmentMessageKind,
        data: {
            name: string;
            date?: string;
            oldDate?: string;
            newDate?: string;
            doctorName: string;
            lang: EmailLang;
        }
    ): string {
        const isEs = data.lang === 'es';

        if (kind === 'reminder') {
            return isEs
                ? `Hola ${data.name}, recordatorio de tu cita con ${data.doctorName} el ${data.date}. Llega 10 minutos antes.`
                : `Hi ${data.name}, reminder for your appointment with ${data.doctorName} on ${data.date}. Please arrive 10 minutes early.`;
        }

        if (kind === 'confirmation') {
            return isEs
                ? `Hola ${data.name}, tu cita con ${data.doctorName} está confirmada para ${data.date}.`
                : `Hi ${data.name}, your appointment with ${data.doctorName} is confirmed for ${data.date}.`;
        }

        if (kind === 'cancellation') {
            return isEs
                ? `Hola ${data.name}, tu cita con ${data.doctorName} programada para ${data.date} fue cancelada.`
                : `Hi ${data.name}, your appointment with ${data.doctorName} scheduled for ${data.date} has been cancelled.`;
        }

        if (kind === 'completed') {
            return isEs
                ? `Hola ${data.name}, tu cita con ${data.doctorName} del ${data.date} fue completada. Gracias por visitarnos.`
                : `Hi ${data.name}, your appointment with ${data.doctorName} on ${data.date} has been completed. Thank you for visiting us.`;
        }

        return isEs
            ? `Hola ${data.name}, tu cita con ${data.doctorName} fue reprogramada de ${data.oldDate} a ${data.newDate}.`
            : `Hi ${data.name}, your appointment with ${data.doctorName} has been rescheduled from ${data.oldDate} to ${data.newDate}.`;
    }
}

export default new WhatsAppService();
