import prisma from '@/lib/prisma';
import nodemailer from 'nodemailer';
import Handlebars from 'handlebars';
import { render } from '@react-email/render';
import { getUnsubscribeUrls } from '@/lib/email/unsubscribeToken';
import { EmailTrackingService } from '@/services/EmailTrackingService';

// React Fallback Templates
import { WelcomeTemplate, ApplicationUpdateTemplate, NotificationTemplate, JobAlertTemplate } from '@/lib/email/templates/Transactional';
import { JobApprovedTemplate, JobRejectedTemplate } from '@/lib/email/templates/JobRelated';
import { NewMessageTemplate } from '@/lib/email/templates/Messaging';
import { InterviewInvitationTemplate } from '@/lib/email/templates/Interview';
import {
    PasswordResetTemplate,
    ActionConfirmationTemplate,
    SecurityAlertTemplate,
    TwoFactorCodeTemplate,
    EmailVerificationTemplate
} from '@/lib/email/templates/Security';
import {
    NewApplicationDigestTemplate,
    ApplicationReceivedTemplate,
    ApplicationStatusUpdateTemplate,
    ApplicationRejectedTemplate,
    CandidateShortlistedTemplate
} from '@/lib/email/templates/ApplicationNotify';
import { InterviewReminderTemplate } from '@/lib/email/templates/InterviewReminders';

const FROM_EMAIL = process.env.EMAIL_FROM || process.env.SMTP_USER || 'noreply@yourdomain.com';
const APP_NAME = 'Proten Job Board';
const APP_URL = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';

/**
 * Maps system event types to their hardcoded React fallback templates and static subject lines.
 */
const FALLBACK_TEMPLATES: Record<string, { getSubject: (payload: any) => string; renderHtml: (payload: any) => string | Promise<string> }> = {
    'welcome': {
        getSubject: () => 'Welcome to Proten Job Board! 🎉',
        renderHtml: (payload) => WelcomeTemplate({ name: payload.name || payload.firstName, loginUrl: payload.loginUrl }),
    },
    'email_verification': {
        getSubject: () => 'Verify Your Email Address',
        renderHtml: (payload) => EmailVerificationTemplate(payload),
    },
    'password_reset': {
        getSubject: () => 'Reset Your Password',
        renderHtml: (payload) => PasswordResetTemplate(payload),
    },
    'password_changed': {
        getSubject: () => 'Your Password Was Changed',
        renderHtml: (payload) => ActionConfirmationTemplate({
            firstName: payload.firstName,
            title: 'Password Changed Successfully',
            message: `Your password was successfully changed on ${new Date().toLocaleDateString()}.`
        }),
    },
    'account_deleted': {
        getSubject: () => 'Account Deletion Request',
        renderHtml: (payload) => ActionConfirmationTemplate({
            firstName: payload.firstName,
            title: 'Confirm Account Deletion',
            message: 'We received a request to delete your account. This action is irreversible.'
        })
    },
    'new_login': {
        getSubject: () => 'New Login to Your Account',
        renderHtml: (payload) => SecurityAlertTemplate(payload),
    },
    '2fa_code': {
        getSubject: () => 'Your Login Code',
        renderHtml: (payload) => TwoFactorCodeTemplate(payload),
    },
    'job_approved': {
        getSubject: (payload: any) => `✅ Your job posting "${payload.jobTitle}" has been approved!`,
        renderHtml: (payload: any) => JobApprovedTemplate(payload),
    },
    'job_rejected': {
        getSubject: (payload: any) => `Action Required: Your job posting "${payload.jobTitle}" was not approved`,
        renderHtml: (payload: any) => JobRejectedTemplate(payload),
    },
    'interview_invite': {
        getSubject: (payload: any) => `Interview Invitation: ${payload.role} at ${payload.company}`,
        renderHtml: (payload: any) => InterviewInvitationTemplate(payload),
    },
    'new_message': {
        getSubject: (payload: any) => `New message from ${payload.senderName} `,
        renderHtml: (payload: any) => NewMessageTemplate(payload),
    },
    'application_update': {
        getSubject: (payload: any) => `Update on your application for ${payload.jobTitle}`,
        renderHtml: (payload: any) => ApplicationUpdateTemplate(payload),
    },
    'notification': {
        getSubject: (payload: any) => payload.title,
        renderHtml: (payload: any) => NotificationTemplate(payload),
    },
    'job_alert': {
        getSubject: (payload: any) => `New jobs for your alert: "${payload.alertName}"`,
        renderHtml: (payload: any) => JobAlertTemplate(payload),
    },
    'employer_new_application_digest': {
        getSubject: (payload: any) => `${payload.applicationsCount} New Application(s) for ${payload.jobTitle}`,
        renderHtml: (payload: any) => render(NewApplicationDigestTemplate(payload)),
    },
    'employer_candidate_shortlisted': {
        getSubject: (payload: any) => `Top Candidate Shortlisted: ${payload.candidateName}`,
        renderHtml: (payload: any) => render(CandidateShortlistedTemplate(payload)),
    },
    'candidate_application_received': {
        getSubject: (payload: any) => `Application Received - ${payload.jobTitle} at ${payload.companyName}`,
        renderHtml: (payload: any) => render(ApplicationReceivedTemplate(payload)),
    },
    'candidate_application_status_update': {
        getSubject: (payload: any) => `Application Update - ${payload.jobTitle}`,
        renderHtml: (payload: any) => render(ApplicationStatusUpdateTemplate(payload)),
    },
    'candidate_application_rejected': {
        getSubject: (payload: any) => `Update regarding ${payload.jobTitle} at ${payload.companyName}`,
        renderHtml: (payload: any) => render(ApplicationRejectedTemplate(payload)),
    },
    'interview_reminder': {
        getSubject: (payload: any) => {
            const type = payload.reminderType || '24h';
            if (type === 'rescheduled') return `Interview Rescheduled: ${payload.jobTitle}`;
            if (type === 'cancelled') return `Interview Cancelled: ${payload.jobTitle}`;
            return `Interview Reminder: ${payload.jobTitle} at ${payload.companyName}`;
        },
        renderHtml: (payload: any) => render(InterviewReminderTemplate(payload)),
    }
};

// ─── Priority Assignment ─────────────────────────────────────────────
const PRIORITY_MAP: Record<string, number> = {
    // Critical (1) — user is waiting
    'password_reset': 1,
    'email_verification': 1,
    '2fa_code': 1,
    // High (2) — time-sensitive
    'interview_reminder': 2,
    'interview_invite': 2,
    'new_login': 2,
    'password_changed': 2,
    'account_deleted': 2,
    // Normal (3) — standard
    'welcome': 3,
    'application_update': 3,
    'candidate_application_received': 3,
    'candidate_application_status_update': 3,
    'candidate_application_rejected': 3,
    'employer_new_application_digest': 3,
    'employer_candidate_shortlisted': 3,
    'job_approved': 3,
    'job_rejected': 3,
    'new_message': 3,
    // Low (4) — can wait
    'job_alert': 4,
    'notification': 4,
};

const CATEGORY_MAP: Record<string, string> = {
    'password_reset': 'transactional',
    'email_verification': 'transactional',
    '2fa_code': 'transactional',
    'new_login': 'transactional',
    'password_changed': 'transactional',
    'account_deleted': 'transactional',
    'welcome': 'transactional',
    'interview_reminder': 'transactional',
    'interview_invite': 'transactional',
    'job_alert': 'alert',
    'notification': 'marketing',
    'employer_new_application_digest': 'digest',
};

// Email types that must be sent immediately without waiting for cron
const IMMEDIATE_SEND_TYPES = ['password_reset', 'email_verification', '2fa_code'];

let _transporter: nodemailer.Transporter | null = null;
function getTransporter() {
    if (!_transporter) {
        _transporter = nodemailer.createTransport({
            host: process.env.SMTP_HOST,
            port: Number(process.env.SMTP_PORT) || 587,
            secure: Number(process.env.SMTP_PORT) === 465,
            auth: {
                user: process.env.SMTP_USER,
                pass: process.env.SMTP_PASS,
            },
        });
    }
    return _transporter;
}

// Type matching the EmailQueue records returned by Prisma
type EmailQueueRecord = {
    id: string;
    type: string;
    to: string;
    user_id: string | null;
    payload: any;
    attempts: number;
    max_attempts: number;
};

export class EmailQueueService {

    // Email types that MUST always be sent regardless of preferences (transactional/security)
    static readonly TRANSACTIONAL_TYPES = [
        'email_verification', 'password_reset', 'password_changed',
        'new_login', '2fa_code', 'account_deleted'
    ];

    // Map email types to notification categories for preference lookup
    static readonly TYPE_TO_CATEGORY: Record<string, string> = {
        'job_alert': 'job_alerts',
        'application_update': 'applications',
        'candidate_application_received': 'applications',
        'candidate_application_status_update': 'applications',
        'candidate_application_rejected': 'applications',
        'employer_new_application_digest': 'new_applications',
        'employer_candidate_shortlisted': 'new_applications',
        'interview_invite': 'interviews',
        'interview_reminder': 'interviews',
        'new_message': 'messages',
        'job_approved': 'job_status',
        'job_rejected': 'job_status',
        'notification': 'platform_updates',
    };

    /**
     * Check if an email can be sent based on user preferences.
     */
    static async canSendEmail(userId: string | null, emailType: string): Promise<{ allowed: boolean; reason?: string }> {
        if (this.TRANSACTIONAL_TYPES.includes(emailType)) {
            return { allowed: true };
        }

        if (!userId) return { allowed: true };

        try {
            const user = await prisma.user.findUnique({
                where: { id: userId },
                select: { email: true }
            });

            if (user) {
                const suppressed = await prisma.emailSuppression.findUnique({
                    where: { email: user.email }
                });
                if (suppressed) {
                    return { allowed: false, reason: 'email_suppressed' };
                }
            }

            const prefs = await prisma.emailPreference.findUnique({
                where: { user_id: userId }
            });

            if (prefs) {
                if (prefs.unsubscribed_all) {
                    return { allowed: false, reason: 'unsubscribed_all' };
                }
                if (prefs.global_pause_until && new Date(prefs.global_pause_until) > new Date()) {
                    return { allowed: false, reason: 'globally_paused' };
                }
            }

            const category = this.TYPE_TO_CATEGORY[emailType];
            if (category) {
                const catPref = await prisma.notificationSetting.findUnique({
                    where: { user_id_category: { user_id: userId, category } }
                });
                if (catPref && catPref.email === 'off') {
                    return { allowed: false, reason: `category_disabled:${category}` };
                }
            }

            return { allowed: true };
        } catch (error) {
            console.error('[EmailQueue] Error checking send permission:', error);
            return { allowed: true };
        }
    }

    /**
     * Enqueues an email for background processing with priority support.
     * For critical types (password_reset, email_verification, 2fa_code), sends immediately.
     */
    static async enqueueEmail(type: string, to: string, payload: any, userId?: string) {
        // Idempotency: Don't queue the EXACT same email within 60 seconds
        const recentDuplicate = await prisma.emailQueue.findFirst({
            where: {
                type,
                to,
                status: { in: ['PENDING', 'PROCESSING'] },
                created_at: { gte: new Date(Date.now() - 60000) }
            }
        });

        if (recentDuplicate) {
            console.log(`[EmailQueue] Idempotency catch: Skipped duplicate '${type}' email for ${to} within 60s.`);
            return { success: true, queued: false, reason: 'idempotent_duplicate' };
        }

        const priority = PRIORITY_MAP[type] || 3;
        const category = CATEGORY_MAP[type] || 'transactional';
        const maxAttempts = priority <= 2 ? 5 : 3; // Critical/high get more retries

        const queued = await prisma.emailQueue.create({
            data: {
                type,
                to,
                payload,
                user_id: userId,
                status: 'PENDING',
                priority,
                category,
                max_attempts: maxAttempts,
            }
        });

        // For critical email types, send immediately instead of waiting for cron
        if (IMMEDIATE_SEND_TYPES.includes(type)) {
            try {
                await EmailQueueService.processEmailById(queued.id);
            } catch (error) {
                console.error(`[EmailQueue] Immediate send failed for ${type} to ${to}:`, error);
                // Email is still in queue with retry logic — cron will pick it up
            }
        }

        return { success: true, queued: true, id: queued.id };
    }

    /**
     * Processes a single email from the queue by its ID.
     * Used for immediate delivery of critical emails.
     */
    static async processEmailById(id: string): Promise<{ success: boolean }> {
        const email = await prisma.emailQueue.findUnique({ where: { id } });
        if (!email || email.status !== 'PENDING') {
            return { success: false };
        }

        await prisma.emailQueue.update({
            where: { id },
            data: { status: 'PROCESSING' }
        });

        const result = await EmailQueueService.processSingleEmail(email as EmailQueueRecord);
        return { success: result === 'sent' };
    }

    /**
     * Injects open tracking pixel and wraps links for click tracking into email HTML.
     */
    static injectTracking(html: string, emailLogId: string): string {
        // 1. Inject open tracking pixel before </body>
        const trackingPixel = `<img src="${APP_URL}/api/email/track/open/${emailLogId}" width="1" height="1" style="display:none;border:0;" alt="" />`;
        let tracked = html;

        if (tracked.includes('</body>')) {
            tracked = tracked.replace('</body>', `${trackingPixel}</body>`);
        } else {
            tracked += trackingPixel;
        }

        // 2. Wrap links for click tracking (skip unsubscribe and mailto links)
        tracked = tracked.replace(
            /href="(https?:\/\/[^"]+)"/g,
            (match, url) => {
                // Don't track unsubscribe or mailto links
                if (url.includes('/unsubscribe') || url.includes('/email/track/') || url.startsWith('mailto:')) {
                    return match;
                }
                const trackUrl = `${APP_URL}/api/email/track/click/${emailLogId}?url=${encodeURIComponent(url)}`;
                return `href="${trackUrl}"`;
            }
        );

        return tracked;
    }

    /**
     * Sends a single queued email record via SMTP and updates its status.
     * Returns the outcome status string.
     */
    private static async processSingleEmail(email: EmailQueueRecord): Promise<'sent' | 'skipped' | 'failed' | 'dead'> {
        try {
            // Check user preferences before sending
            const sendCheck = await EmailQueueService.canSendEmail(email.user_id, email.type);
            if (!sendCheck.allowed) {
                console.log(`[EmailQueue] Skipped email ${email.id} (${email.type}): ${sendCheck.reason}`);
                await prisma.emailQueue.update({
                    where: { id: email.id },
                    data: { status: 'SKIPPED', last_error: `Preference: ${sendCheck.reason}`, updated_at: new Date() }
                });
                return 'skipped';
            }

            let subject = '';
            let html = '';

            // Check for Admin Template Override in Database
            const dbTemplate = await prisma.adminEmailTemplate.findUnique({
                where: { type: email.type }
            });

            // Inject unsubscribe URLs into the payload
            const enrichedPayload = { ...email.payload as Record<string, any> };
            if (email.user_id) {
                const urls = getUnsubscribeUrls(email.user_id, email.to);
                enrichedPayload.unsubscribeUrl = urls.unsubscribeAll;
                enrichedPayload.managePreferencesUrl = urls.managePreferences;
            }

            if (dbTemplate && dbTemplate.is_active) {
                const subjectTemplate = Handlebars.compile(dbTemplate.subject);
                const bodyTemplate = Handlebars.compile(dbTemplate.html_body);
                subject = subjectTemplate(enrichedPayload);
                html = bodyTemplate(enrichedPayload);
            } else {
                const fallback = FALLBACK_TEMPLATES[email.type];
                if (!fallback) {
                    throw new Error(`No template found for type: ${email.type}`);
                }
                subject = fallback.getSubject(enrichedPayload);
                html = await fallback.renderHtml(enrichedPayload);
            }

            // Send via SMTP
            const info = await getTransporter().sendMail({
                from: `"${APP_NAME}" <${FROM_EMAIL}>`,
                to: email.to,
                subject,
                html,
                attachments: (email.payload as any).attachments || [],
                headers: email.user_id ? {
                    'List-Unsubscribe': `<${getUnsubscribeUrls(email.user_id, email.to).unsubscribeAll}>`,
                    'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click'
                } : {}
            });

            // Create the email log entry
            const emailLog = await prisma.emailLog.create({
                data: {
                    queue_id: email.id,
                    type: email.type,
                    to: email.to,
                    user_id: email.user_id,
                    subject,
                    status: 'SENT',
                    delivery_status: 'sent',
                    provider_id: info.messageId,
                }
            });

            // Record delivery event
            await EmailTrackingService.recordEvent(emailLog.id, 'delivered', {
                provider: 'smtp',
                provider_id: info.messageId,
            });

            // Update queue status
            await prisma.emailQueue.update({
                where: { id: email.id },
                data: { status: 'SENT', updated_at: new Date() }
            });

            return 'sent';

        } catch (error: any) {
            const newAttempts = email.attempts + 1;
            const maxAttempts = email.max_attempts || 3;
            const willRetry = newAttempts < maxAttempts;

            console.error(`[EmailQueue] Failed to send email ${email.id}: `, error);

            if (willRetry) {
                // Exponential backoff: 2^attempt × 60 seconds
                const backoffMs = Math.pow(2, newAttempts) * 60 * 1000;
                const scheduledFor = new Date(Date.now() + backoffMs);

                await prisma.emailQueue.update({
                    where: { id: email.id },
                    data: {
                        status: 'PENDING',
                        attempts: newAttempts,
                        last_error: error.message || 'Unknown error',
                        scheduled_for: scheduledFor,
                        updated_at: new Date(),
                    }
                });

                console.log(`[EmailQueue] Will retry email ${email.id} in ${backoffMs / 1000}s (attempt ${newAttempts}/${maxAttempts})`);
            } else {
                // Move to dead letter queue
                await prisma.emailQueue.update({
                    where: { id: email.id },
                    data: {
                        status: 'DEAD',
                        attempts: newAttempts,
                        last_error: error.message || 'Unknown error',
                        updated_at: new Date(),
                    }
                });

                console.error(`[EmailQueue] Email ${email.id} moved to DEAD letter queue after ${newAttempts} attempts`);
            }

            // Log the failure
            await prisma.emailLog.create({
                data: {
                    queue_id: email.id,
                    type: email.type,
                    to: email.to,
                    user_id: email.user_id,
                    status: 'FAILED',
                    delivery_status: 'sent',
                    error: error.message || 'Unknown error',
                }
            });

            return willRetry ? 'failed' : 'dead';
        }
    }

    /**
     * Processes the email queue with priority ordering and exponential backoff.
     */
    static async processQueue() {
        const now = new Date();

        // Fetch pending emails ordered by priority (1=critical first), then by creation time
        // Only fetch emails that are not scheduled for later
        const pendingEmails = await prisma.emailQueue.findMany({
            where: {
                status: 'PENDING',
                OR: [
                    { scheduled_for: null },
                    { scheduled_for: { lte: now } },
                ],
            },
            take: 50,
            orderBy: [
                { priority: 'asc' },    // Critical (1) first
                { created_at: 'asc' },  // Oldest within priority
            ],
        });

        if (pendingEmails.length === 0) return { processed: 0 };

        // Mark them as processing
        await prisma.emailQueue.updateMany({
            where: { id: { in: pendingEmails.map(e => e.id) } },
            data: { status: 'PROCESSING' }
        });

        let successCount = 0;
        let failCount = 0;
        let deadCount = 0;

        for (const email of pendingEmails) {
            const result = await EmailQueueService.processSingleEmail(email as EmailQueueRecord);
            if (result === 'sent') successCount++;
            else if (result === 'dead') deadCount++;
            else if (result === 'failed') failCount++;
        }

        return {
            processed: pendingEmails.length,
            successful: successCount,
            failed: failCount,
            dead: deadCount,
        };
    }
}
