import db from '../database/models/index.js';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { Op } from 'sequelize';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const seedTemplates = async () => {
    try {
        const templatesDir = path.join(__dirname, '../emailtemplates');

        // Legacy rows used lowercase codes; remove to avoid duplicate keys after rename
        await db.EmailTemplate.destroy({
            where: { templateCode: { [Op.in]: ['opportunity', 'non_opportunity'] } }
        });

        const templates = [
            {
                templateCode: 'OPPORTUNITY',
                description: 'Opportunity link for dealership application assessment',
                subject: 'Action Required: Royal Enfield Dealership Opportunity',
                fileName: 'opportunity.html',
                placeholders: ['applicantName', 'location']
            },
            {
                templateCode: 'NON_OPPORTUNITY',
                description: 'Regret email for non-opportunity applications',
                subject: 'Update on your Royal Enfield Dealership Application',
                fileName: 'non_opportunity.html',
                placeholders: ['applicantName', 'location']
            },
            {
                templateCode: 'INTERVIEW_SCHEDULED',
                description: 'Notification for scheduled interview',
                subject: 'Interview Scheduled: {{applicationId}}',
                fileName: 'interview_scheduled.html',
                placeholders: ['name', 'applicationId', 'level', 'dateTime', 'type', 'location']
            },
            {
                templateCode: 'USER_ASSIGNED',
                description: 'Notification for user assignment to an application',
                subject: 'New Application Assignment: {{applicationId}}',
                fileName: 'user_assigned.html',
                placeholders: ['userName', 'applicationId', 'dealerName', 'participantType']
            },
            {
                templateCode: 'QUESTIONNAIRE_SUBMITTED',
                description: 'Acknowledgement for questionnaire submission',
                subject: 'Questionnaire Submitted Successfully: {{applicationId}}',
                fileName: 'questionnaire_submitted.html',
                placeholders: ['applicantName', 'location', 'applicationId']
            },
            {
                templateCode: 'APPLICANT_SHORTLISTED',
                description: 'Notification for shortlisted applicants',
                subject: 'Congratulations! You are Shortlisted: {{applicationId}}',
                fileName: 'applicant_shortlisted.html',
                placeholders: ['applicantName', 'location', 'applicationId']
            },
            {
                templateCode: 'LOI_ISSUED',
                description: 'Notification when Letter of Intent is issued',
                subject: 'Letter of Intent (LOI) Issued: {{applicationId}}',
                fileName: 'loi_issued.html',
                placeholders: ['applicantName', 'applicationId']
            },
            {
                templateCode: 'LOA_ISSUED',
                description: 'Notification when Letter of Appointment is issued',
                subject: 'Letter of Appointment (LOA) Issued: {{applicationId}}',
                fileName: 'loa_issued.html',
                placeholders: ['applicantName', 'applicationId', 'dealerCode']
            },
            {
                templateCode: 'DEALER_CODE_READY',
                description: 'Notification when SAP Dealer Codes are generated',
                subject: 'SAP Dealer Codes Readiness for {{applicationId}}',
                fileName: 'dealer_code_ready.html',
                placeholders: ['applicantName', 'applicationId', 'salesCode', 'serviceCode']
            },
            {
                templateCode: 'ONBOARDING_STATUS_UPDATE',
                description: 'General onboarding status changes (excluding LOI/LOA/dealer-code specific mails)',
                subject: 'Onboarding Status Update: {{status}} — {{applicationId}}',
                fileName: 'onboarding_status_update.html',
                placeholders: ['applicantName', 'applicationId', 'status', 'reason', 'salesCode', 'serviceCode']
            },
            {
                templateCode: 'EOR_COMPLETED',
                description: 'Notification when EOR readiness is 100% complete',
                subject: 'EOR Readiness 100% Completed: {{applicationId}}',
                fileName: 'eor_completed.html',
                placeholders: ['applicantName', 'applicationId', 'location']
            },
            {
                templateCode: 'RESIGNATION_SUBMITTED',
                description: 'Notification for new Resignation submission',
                subject: 'New Resignation Request: {{resignationId}}',
                fileName: 'resignation_submitted.html',
                placeholders: ['dealerName', 'resignationId', 'lwd']
            },
            {
                templateCode: 'RESIGNATION_APPROVED',
                description: 'Notification when Resignation is approved',
                subject: 'Resignation Request Approved: {{resignationId}}',
                fileName: 'resignation_approved.html',
                placeholders: ['dealerName', 'resignationId', 'lwd']
            },
            {
                templateCode: 'RESIGNATION_LETTER_DISPATCHED_DEALER',
                description: 'Notification sent to the dealer when the DD Admin dispatches the resignation acceptance letter (letter is delivered as an email attachment)',
                subject: 'Resignation Acceptance Letter Dispatched: {{resignationId}}',
                fileName: 'resignation_letter_dispatched_dealer.html',
                placeholders: ['dealerName', 'resignationId', 'lwd', 'dispatchedBy', 'link', 'ctaLabel']
            },
            {
                templateCode: 'TERMINATION_INITIATED',
                description: 'Notification for new Termination request initiation',
                subject: 'Dealer Termination Case Initiated — {{requestId}}',
                fileName: 'termination_initiated.html',
                placeholders: ['recipientName', 'dealerName', 'requestId', 'category', 'initiatedBy', 'currentStage', 'remarks', 'link', 'ctaLabel']
            },
            {
                templateCode: 'TERMINATION_SCN_ISSUED',
                description: 'Notification for Show Cause Notice issuance',
                subject: 'URGENT: Show Cause Notice Issued: {{terminationId}}',
                fileName: 'termination_scn.html',
                placeholders: ['dealerName', 'terminationId', 'deadline', 'link', 'ctaLabel']
            },
            {
                templateCode: 'FNF_INITIATED',
                description: 'Notification for F&F Settlement initiation',
                subject: 'F&F Settlement Initiated — {{requestId}}',
                fileName: 'fnf_initiated.html',
                placeholders: ['recipientName', 'dealerName', 'requestId', 'initiatedBy', 'lwd', 'link', 'ctaLabel']
            },
            {
                templateCode: 'FNF_LWD_READY',
                description: 'Notifies DD Admin / DD Lead when Last Working Day is reached and Push to F&F can be used',
                subject: 'LWD Reached — Initiate F&F for {{requestId}}',
                fileName: 'fnf_lwd_ready.html',
                placeholders: ['recipientName', 'dealerName', 'requestId', 'requestType', 'lwd', 'link', 'ctaLabel']
            },
            {
                templateCode: 'FNF_SUMMARY_PREPARED',
                description: 'Notification to Finance team when F&F summary is ready for review',
                subject: 'F&F Settlement Summary Prepared: {{fnfId}}',
                fileName: 'fnf_summary_prepared.html',
                placeholders: ['fnfId', 'dealerName', 'netAmount', 'link', 'ctaLabel']
            },
            {
                templateCode: 'FNF_SETTLEMENT_APPROVED',
                description: 'Notification when Finance approves the final settlement',
                subject: 'F&F Settlement Approved: {{fnfId}}',
                fileName: 'fnf_settlement_approved.html',
                placeholders: ['fnfId', 'dealerName', 'settlementAmount', 'link', 'ctaLabel']
            },
            {
                templateCode: 'ONBOARDING_PAYMENT_VERIFIED',
                description: 'Notification when Security Deposit or initial payment is verified',
                subject: 'Payment Verified: {{applicationId}}',
                fileName: 'onboarding_payment_verified.html',
                placeholders: ['applicationId', 'dealerName', 'paymentType', 'amount', 'link']
            },
            {
                templateCode: 'WORKNOTE_NOTIFICATION',
                description: 'Notification for new work note or update',
                subject: 'New Update on Application: {{applicationId}}',
                fileName: 'worknote_notification.html',
                placeholders: ['userName', 'applicationId', 'dealerName', 'message']
            },
            {
                templateCode: 'GENERIC_NOTIFICATION',
                description: 'Standard multi-purpose notification',
                subject: '{{title}}',
                fileName: 'generic_notification.html',
                placeholders: ['title', 'message']
            },
            {
                templateCode: 'QUESTIONNAIRE_REMINDER',
                description: 'Periodic reminder to complete assessment',
                subject: 'Reminder: Complete your Dealer Assessment',
                fileName: 'questionnaire_reminder.html',
                placeholders: ['applicantName', 'location']
            },
            {
                templateCode: 'CONSTITUTIONAL_CHANGE_SUBMITTED',
                description: 'Notification for new Constitutional Change request',
                subject: 'New Constitutional Change Request: {{requestId}}',
                fileName: 'constitutional_change_submitted.html',
                placeholders: ['dealerName', 'changeType', 'requestId']
            },
            {
                templateCode: 'RESIGNATION_UPDATE',
                description: 'General status update for Resignation',
                subject: 'Resignation Status Update: {{status}}',
                fileName: 'resignation_update.html',
                placeholders: ['dealerName', 'status', 'remarks']
            },
            {
                templateCode: 'TERMINATION_LETTER_ISSUED',
                description: 'Internal alert to DD-Lead, Admin, and Finance when termination letter is generated',
                subject: 'Termination Letter Generated: {{requestId}}',
                fileName: 'termination_letter_issued.html',
                placeholders: ['recipientName', 'dealerName', 'requestId', 'link', 'ctaLabel']
            },
            {
                templateCode: 'TERMINATION_FINAL_CLOSURE_DEALER',
                description: 'Final closure notification sent to the dealer upon termination completion',
                subject: 'Official Notice: Termination of Dealership — {{requestId}}',
                fileName: 'termination_final_closure.html',
                placeholders: ['dealerName', 'requestId', 'terminationDate', 'link', 'ctaLabel']
            },
            {
                templateCode: 'TERMINATION_UPDATE',
                description: 'General status update for Termination',
                subject: 'Termination Status Update: {{status}}',
                fileName: 'termination_update.html',
                placeholders: ['dealerName', 'status', 'remarks']
            },
            {
                templateCode: 'INAUGURATION_COMPLETED',
                description: 'Notification to relevant teams when a dealership inauguration is logged',
                subject: 'Dealership Inauguration Logged: {{applicationId}}',
                fileName: 'inauguration_completed.html',
                placeholders: ['dealerName', 'applicationId', 'location', 'date']
            },
            {
                templateCode: 'CONSTITUTIONAL_CHANGE_APPROVED',
                description: 'Final approval notification for Constitutional Change',
                subject: 'Constitutional Change Approved — {{requestId}}',
                fileName: 'constitutional_change_approved.html',
                placeholders: ['dealerName', 'requestId', 'proposedConstitution', 'link']
            },
            {
                templateCode: 'CONSTITUTIONAL_CHANGE_UPDATE',
                description: 'General status update for Constitutional Change',
                subject: 'Constitutional Change Update: {{status}}',
                fileName: 'constitutional_change_update.html',
                placeholders: ['dealerName', 'status', 'remarks']
            },
            {
                templateCode: 'RESIGNATION_RECEIVED',
                description: 'Acknowledgement to dealer when resignation request is submitted',
                subject: 'We received your resignation — {{resignationId}}',
                fileName: 'resignation_received.html',
                placeholders: ['dealerName', 'resignationId', 'lwd']
            },
            {
                templateCode: 'RELOCATION_RECEIVED',
                description: 'Acknowledgement to dealer when relocation request is submitted',
                subject: 'Relocation request received — {{requestId}}',
                fileName: 'relocation_received.html',
                placeholders: ['dealerName', 'requestId']
            },
            {
                templateCode: 'RELOCATION_SUBMITTED',
                description: 'Internal notify (e.g. ASM) when a dealer submits relocation',
                subject: 'New relocation request: {{requestId}}',
                fileName: 'relocation_submitted.html',
                placeholders: ['dealerName', 'requestId', 'outletCode']
            },
            {
                templateCode: 'RELOCATION_APPROVED',
                description: 'Final approval notification for Relocation',
                subject: 'Relocation Approved — {{requestId}}',
                fileName: 'relocation_approved.html',
                placeholders: ['dealerName', 'requestId', 'newLocation', 'link']
            },
            {
                templateCode: 'RELOCATION_UPDATE',
                description: 'Dealer-visible status updates during relocation workflow',
                subject: 'Relocation update — {{requestId}} ({{status}})',
                fileName: 'relocation_update.html',
                placeholders: ['dealerName', 'requestId', 'status', 'remarks']
            },
            {
                templateCode: 'SLA_BREACH_WARNING',
                description: 'Email when an application SLA tracking record breaches deadline',
                subject: 'SLA breach: {{applicationId}} — {{stageName}}',
                fileName: 'sla_breach_warning.html',
                placeholders: ['applicationId', 'stageName', 'currentStage']
            },
            {
                templateCode: 'SLA_REMINDER',
                description: 'Reminder sent before SLA breach',
                subject: 'SLA Reminder: {{applicationId}} — {{stageName}}',
                fileName: 'sla_reminder.html',
                placeholders: ['applicationId', 'stageName', 'link']
            },
            {
                templateCode: 'SLA_BREACH',
                description: 'Notification sent when SLA is breached',
                subject: 'SLA BREACHED: {{applicationId}} — {{stageName}}',
                fileName: 'sla_breach.html',
                placeholders: ['applicationId', 'stageName', 'link']
            },
            {
                templateCode: 'SLA_ESCALATION',
                description: 'Notification sent for multi-level SLA escalations',
                subject: 'SLA ESCALATION [L{{level}}]: {{applicationId}} — {{stageName}}',
                fileName: 'sla_escalation.html',
                placeholders: ['applicationId', 'stageName', 'level', 'timeValue', 'timeUnit', 'link']
            },
            {
                templateCode: 'WORKFLOW_ACTION_REQUIRED',
                description: 'Turn-based notification for next reviewer/actor in any workflow',
                subject: 'Action Required: {{requestId}} — {{targetStage}}',
                fileName: 'workflow_action_required.html',
                placeholders: ['requestId', 'dealerName', 'targetStage', 'remarks', 'link', 'ctaLabel']
            },
            {
                templateCode: 'WORKFLOW_STATUS_UPDATE_DEALER',
                description: 'Status update notification sent to dealer for interim workflow stages',
                subject: 'Update on Your Request — {{requestId}}',
                fileName: 'workflow_status_update_dealer.html',
                placeholders: ['dealerName', 'requestId', 'targetStage', 'remarks', 'link', 'ctaLabel']
            },
            {
                templateCode: 'PROSPECT_DOCUMENT_REQUEST',
                description: 'Post-shortlist or follow-up document request to the applicant',
                subject: 'Documents Required — Royal Enfield Dealership Application {{applicationId}}',
                fileName: 'prospect_document_request.html',
                placeholders: ['applicantName', 'location', 'applicationId', 'dueDate', 'documentList', 'link', 'ctaLabel', 'isShortlistContext']
            },
            {
                templateCode: 'STATUTORY_DOCUMENT_REQUEST',
                description: 'After LOI: request statutory and compliance documents for authorisation',
                subject: 'Statutory Documents Required — {{applicationId}}',
                fileName: 'statutory_document_request.html',
                placeholders: ['applicantName', 'applicationId', 'dueDate', 'statutoryList', 'link', 'ctaLabel']
            },
            {
                templateCode: 'DOCUMENT_SUBMISSION_REMINDER',
                description: 'Reminder for pending document uploads (manual / bulk send)',
                subject: 'Reminder: Pending documents for {{applicationId}}',
                fileName: 'document_submission_reminder.html',
                placeholders: ['applicantName', 'applicationId', 'pendingDocuments', 'dueDate', 'link', 'ctaLabel']
            },
            {
                templateCode: 'DOCUMENT_RECEIVED_ACKNOWLEDGEMENT',
                description: 'Acknowledgement when applicant uploads a document',
                subject: 'Documents received — {{applicationId}}',
                fileName: 'document_received_acknowledgement.html',
                placeholders: ['applicantName', 'applicationId', 'documentCategory', 'documentName', 'receivedOn', 'link', 'ctaLabel']
            },
            {
                templateCode: 'DOCUMENT_REJECTED_RESUBMIT',
                description: 'When DD-Admin / Legal rejects an onboarding document',
                subject: 'Action Required: Re-submit documents for {{applicationId}}',
                fileName: 'document_rejected_resubmit.html',
                placeholders: ['applicantName', 'applicationId', 'documentName', 'rejectionReason', 'dueDate', 'link', 'ctaLabel']
            },
            {
                templateCode: 'FDD_DOCUMENT_REQUEST',
                description: 'Applicant checklist when FDD agency is assigned',
                subject: 'FDD Documents Required — {{applicationId}}',
                fileName: 'fdd_document_request.html',
                placeholders: ['applicantName', 'applicationId', 'fddPartnerName', 'dueDate', 'documentChecklist', 'link', 'ctaLabel']
            },
            {
                templateCode: 'LOI_ACKNOWLEDGEMENT_REQUEST',
                description: 'Chase applicant to acknowledge LOI on the portal',
                subject: 'Action Required: Acknowledge your Letter of Intent — {{applicationId}}',
                fileName: 'loi_acknowledgement_request.html',
                placeholders: ['applicantName', 'applicationId', 'dueDate', 'link', 'ctaLabel']
            },
            {
                templateCode: 'SECURITY_DEPOSIT_REQUEST',
                description: 'After LOI acknowledgement: Security Deposit payment instructions',
                subject: 'Security Deposit Payment Required — {{applicationId}}',
                fileName: 'security_deposit_request.html',
                placeholders: ['applicantName', 'applicationId', 'amount', 'dueDate', 'bankDetails', 'link', 'ctaLabel']
            },
            {
                templateCode: 'DEALERSHIP_AGREEMENT_SIGNATURE_REQUEST',
                description: 'After LOA: request e-signature on dealership agreement',
                subject: 'Dealership Agreement ready for signature — {{applicationId}}',
                fileName: 'dealership_agreement_signature_request.html',
                placeholders: ['applicantName', 'applicationId', 'dealerCode', 'dueDate', 'link', 'ctaLabel']
            },
            {
                templateCode: 'ARCHITECTURAL_PLAN_REQUEST',
                description: 'When architecture lead is assigned: site inputs from applicant',
                subject: 'Architectural Plan & Site Inputs Required — {{applicationId}}',
                fileName: 'architectural_plan_request.html',
                placeholders: ['applicantName', 'applicationId', 'architectName', 'dueDate', 'inputsList', 'link', 'ctaLabel']
            }
        ];

        for (const t of templates) {
            let body = '';
            try {
                const filePath = path.join(templatesDir, t.fileName);
                if (fs.existsSync(filePath)) {
                    body = fs.readFileSync(filePath, 'utf-8');
                } else {
                    console.warn(`File not found: ${t.fileName}. Creating a placeholder body.`);
                    body = `<html><body><h1>${t.description}</h1><p>This is a placeholder for ${t.templateCode}</p></body></html>`;
                }

                await db.EmailTemplate.upsert({
                    templateCode: t.templateCode,
                    description: t.description,
                    subject: t.subject,
                    body: body,
                    placeholders: t.placeholders,
                    isActive: true
                });
                console.log(`Seeded/Updated template: ${t.templateCode}`);
            } catch (err) {
                console.error(`Failed to seed ${t.templateCode}:`, err);
            }
        }

        console.log('Email template seeding completed.');
        process.exit(0);
    } catch (error) {
        console.error('Seeding error:', error);
        process.exit(1);
    }
};

seedTemplates();
