import { Resend } from 'resend';
import {
    clinicalRecordTemplate,
    dentalRecordTemplate,
    forgotPasswordTemplate,
    subscriptionConfirmationTemplate,
    welcomeEmailTemplate,
    patientAddedTemplate,
    appointmentReminderTemplate,
    appointmentConfirmationTemplate,
    appointmentCancellationTemplate,
    appointmentCompletedTemplate,
    appointmentRescheduledTemplate,
    newDoctorCredentialsTemplate,
    EmailLang,
} from '../utils/emailTemplates';

const subjects: Record<string, Record<EmailLang, string>> = {
    appointmentReminder: {
        en: 'Appointment Reminder - Medklinix',
        es: 'Recordatorio de Cita - Medklinix',
    },
    appointmentConfirmation: {
        en: 'Appointment Confirmed - Medklinix',
        es: 'Cita Confirmada - Medklinix',
    },
    appointmentCancellation: {
        en: 'Appointment Cancelled - Medklinix',
        es: 'Cita Cancelada - Medklinix',
    },
    appointmentRescheduled: {
        en: 'Appointment Rescheduled - Medklinix',
        es: 'Cita Reprogramada - Medklinix',
    },
    appointmentCompleted: {
        en: 'Appointment Completed - Medklinix',
        es: 'Cita Completada - Medklinix',
    },
    doctorCredentials: {
        en: 'Your Medklinix Login Credentials',
        es: 'Tus Credenciales de Acceso - Medklinix',
    },
    welcome: {
        en: 'Welcome to Medklinix',
        es: 'Bienvenido a Medklinix',
    },
    patientAdded: {
        en: 'Patient Profile Created - Medklinix',
        es: 'Perfil de Paciente Creado - Medklinix',
    },
    passwordReset: {
        en: 'Reset Your Password - Medklinix',
        es: 'Restablecer Tu Contraseña - Medklinix',
    },
    subscriptionConfirmation: {
        en: 'Subscription Confirmed - Medklinix',
        es: 'Suscripción Confirmada - Medklinix',
    },
    clinicalRecord: {
        en: 'New Clinical Record Added - Medklinix',
        es: 'Nuevo Registro Clínico - Medklinix',
    },
    dentalRecord: {
        en: 'New Dental Record Added - Medklinix',
        es: 'Nuevo Registro Dental - Medklinix',
    },
};

export class EmailService {
    private resend: Resend;
    private fromEmail: string;

    constructor() {
        this.resend = new Resend(process.env.RESEND_API_KEY);
        this.fromEmail = process.env.EMAIL_FROM || 'onboarding@resend.dev';
    }

    // ─── Appointment Emails ───

    async sendAppointmentReminder(to: string, name: string, date: string, doctorName: string, lang: EmailLang = 'en'): Promise<boolean> {
        return this.sendEmail(
            to,
            subjects.appointmentReminder[lang],
            appointmentReminderTemplate(name, date, doctorName, lang)
        );
    }

    async sendAppointmentConfirmation(to: string, name: string, date: string, doctorName: string, lang: EmailLang = 'en'): Promise<boolean> {
        return this.sendEmail(
            to,
            subjects.appointmentConfirmation[lang],
            appointmentConfirmationTemplate(name, date, doctorName, lang)
        );
    }

    async sendAppointmentCancellation(to: string, name: string, date: string, doctorName: string, lang: EmailLang = 'en'): Promise<boolean> {
        return this.sendEmail(
            to,
            subjects.appointmentCancellation[lang],
            appointmentCancellationTemplate(name, date, doctorName, lang)
        );
    }

    async sendAppointmentRescheduled(
        to: string,
        name: string,
        oldDate: string,
        newDate: string,
        doctorName: string,
        lang: EmailLang = 'en'
    ): Promise<boolean> {
        return this.sendEmail(
            to,
            subjects.appointmentRescheduled[lang],
            appointmentRescheduledTemplate(name, oldDate, newDate, doctorName, lang)
        );
    }

    async sendAppointmentCompleted(to: string, name: string, date: string, doctorName: string, lang: EmailLang = 'en'): Promise<boolean> {
        return this.sendEmail(
            to,
            subjects.appointmentCompleted[lang],
            appointmentCompletedTemplate(name, date, doctorName, lang)
        );
    }

    async sendNewDoctorCredentials(to: string, name: string, email: string, password: string, ownerName: string, lang: EmailLang = 'en'): Promise<boolean> {
        return this.sendEmail(
            to,
            subjects.doctorCredentials[lang],
            newDoctorCredentialsTemplate(name, email, password, ownerName, lang)
        );
    }

    // ─── General Emails ───

    async sendWelcomeEmail(to: string, name: string, lang: EmailLang = 'en'): Promise<boolean> {
        return this.sendEmail(to, subjects.welcome[lang], welcomeEmailTemplate(name, lang));
    }

    async sendPatientAddedEmail(to: string, name: string, lang: EmailLang = 'en'): Promise<boolean> {
        return this.sendEmail(to, subjects.patientAdded[lang], patientAddedTemplate(name, lang));
    }

    async sendPasswordResetEmail(to: string, resetLink: string, lang: EmailLang = 'en'): Promise<boolean> {
        return this.sendEmail(to, subjects.passwordReset[lang], forgotPasswordTemplate(resetLink, lang));
    }

    async sendSubscriptionConfirmationEmail(to: string, name: string, planName: string, lang: EmailLang = 'en'): Promise<boolean> {
        return this.sendEmail(to, subjects.subscriptionConfirmation[lang], subscriptionConfirmationTemplate(name, planName, lang));
    }

    async sendClinicalRecordEmail(to: string, name: string, date: string, type: string, lang: EmailLang = 'en'): Promise<boolean> {
        return this.sendEmail(to, subjects.clinicalRecord[lang], clinicalRecordTemplate(name, date, type, lang));
    }

    async sendDentalRecordEmail(to: string, name: string, date: string, treatment: string, lang: EmailLang = 'en'): Promise<boolean> {
        return this.sendEmail(to, subjects.dentalRecord[lang], dentalRecordTemplate(name, date, treatment, lang));
    }

    // ─── Core Sender (DRY) ───

    private async sendEmail(to: string, subject: string, html: string): Promise<boolean> {
        try {
            const { data, error } = await this.resend.emails.send({
                from: this.fromEmail,
                to: [to],
                subject,
                html,
            });

            if (error) {
                console.error(`[EmailService] Error sending "${subject}" to ${to}:`, error);
                return false;
            }

            console.log(`[EmailService] ✓ "${subject}" sent to ${to} (ID: ${data?.id})`);
            return true;
        } catch (err) {
            console.error(`[EmailService] Exception sending "${subject}" to ${to}:`, err);
            return false;
        }
    }
}

export default new EmailService();
