/**
 * Email Template Controller
 * Handles HTTP requests for email template management (Super Admin only)
 */

const { catchAsyncErrors } = require('../middlewares/catchAsyncErrors');
const emailTemplateService = require('../services/emailTemplate.service');
const EmailTemplate = require('../models/emailTemplate.model');
const ErrorHandler = require('../utils/ErrorHandler');

/**
 * Get all email templates with filters and pagination
 * GET /api/super-admin/email-templates
 */
exports.getAllTemplates = catchAsyncErrors(async (req, res, next) => {
    const { category, emailType, isActive, search, page = 1, limit = 10 } = req.query;

    const filters = {};
    if (category) filters.category = category;
    if (emailType) filters.emailType = emailType;
    if (isActive !== undefined) filters.isActive = isActive === 'true';
    if (search) filters.search = search;

    const result = await emailTemplateService.getAllTemplates(
        filters,
        { page: parseInt(page), limit: parseInt(limit) }
    );

    res.status(200).json({
        success: true,
        message: 'Email templates retrieved successfully',
        data: result
    });
});

/**
 * Get single email template by ID
 * GET /api/super-admin/email-templates/:id
 */
exports.getTemplateById = catchAsyncErrors(async (req, res, next) => {
    const { id } = req.params;

    const template = await emailTemplateService.getTemplateById(id);

    res.status(200).json({
        success: true,
        message: 'Email template retrieved successfully',
        data: template
    });
});

/**
 * Get template by email type (for internal use)
 * GET /api/super-admin/email-templates/type/:emailType
 */
exports.getTemplateByEmailType = catchAsyncErrors(async (req, res, next) => {
    const { emailType } = req.params;

    const template = await emailTemplateService.getTemplateByEmailType(emailType);

    res.status(200).json({
        success: true,
        message: 'Email template retrieved successfully',
        data: template
    });
});

/**
 * Create new email template
 * POST /api/super-admin/email-templates
 */
exports.createTemplate = catchAsyncErrors(async (req, res, next) => {
    const { templateName, emailType, subject, htmlContent, textContent, variables, requiredVariables, isDefault, description, category } = req.body;

    // Validate required fields
    if (!templateName || !emailType || !subject || !htmlContent) {
        return next(new ErrorHandler('Missing required fields: templateName, emailType, subject, htmlContent', 400));
    }

    const template = await emailTemplateService.createTemplate(
        {
            templateName,
            emailType,
            subject,
            htmlContent,
            textContent,
            variables,
            requiredVariables,
            isDefault,
            description,
            category
        },
        req.user._id
    );

    res.status(201).json({
        success: true,
        message: 'Email template created successfully',
        data: template
    });
});

/**
 * Update email template
 * PUT /api/super-admin/email-templates/:id
 */
exports.updateTemplate = catchAsyncErrors(async (req, res, next) => {
    const { id } = req.params;
    const updateData = req.body;

    const template = await emailTemplateService.updateTemplate(id, updateData, req.user._id);

    res.status(200).json({
        success: true,
        message: 'Email template updated successfully',
        data: template
    });
});

/**
 * Delete email template
 * DELETE /api/super-admin/email-templates/:id
 */
exports.deleteTemplate = catchAsyncErrors(async (req, res, next) => {
    const { id } = req.params;

    const result = await emailTemplateService.deleteTemplate(id);

    res.status(200).json({
        success: true,
        message: result.message,
        data: {}
    });
});

/**
 * Duplicate email template
 * POST /api/super-admin/email-templates/:id/duplicate
 */
exports.duplicateTemplate = catchAsyncErrors(async (req, res, next) => {
    const { id } = req.params;
    const { newName } = req.body;

    if (!newName) {
        return next(new ErrorHandler('newName is required', 400));
    }

    const template = await emailTemplateService.duplicateTemplate(id, newName, req.user._id);

    res.status(201).json({
        success: true,
        message: 'Email template duplicated successfully',
        data: template
    });
});

/**
 * Get template preview with variable substitution
 * POST /api/super-admin/email-templates/:id/preview
 */
exports.getTemplatePreview = catchAsyncErrors(async (req, res, next) => {
    const { id } = req.params;
    const { variables = {} } = req.body;

    const preview = await emailTemplateService.getTemplatePreview(id, variables);

    res.status(200).json({
        success: true,
        message: 'Template preview generated successfully',
        data: preview
    });
});

/**
 * Get template statistics
 * GET /api/super-admin/email-templates/stats
 */
exports.getTemplateStats = catchAsyncErrors(async (req, res, next) => {
    const stats = await emailTemplateService.getTemplateStats();

    res.status(200).json({
        success: true,
        message: 'Template statistics retrieved successfully',
        data: stats
    });
});

/**
 * Seed default templates (run once during setup)
 * POST /api/super-admin/email-templates/seed
 */
exports.seedDefaultTemplates = catchAsyncErrors(async (req, res, next) => {
    const result = await emailTemplateService.seedDefaultTemplates(req.user._id);

    res.status(201).json({
        success: true,
        message: result.message,
        data: result
    });
});

/**
 * Get global header template
 * GET /api/super/email-templates/global/header
 */
exports.getGlobalHeader = catchAsyncErrors(async (req, res, next) => {
    const template = await EmailTemplate.getGlobalHeader();

    res.status(200).json({
        success: true,
        message: 'Global header template retrieved successfully',
        data: template
    });
});

/**
 * Get global footer template
 * GET /api/super/email-templates/global/footer
 */
exports.getGlobalFooter = catchAsyncErrors(async (req, res, next) => {
    const template = await EmailTemplate.getGlobalFooter();

    res.status(200).json({
        success: true,
        message: 'Global footer template retrieved successfully',
        data: template
    });
});

/**
 * Update or create global header template
 * PUT /api/super/email-templates/global/header
 */
exports.updateGlobalHeader = catchAsyncErrors(async (req, res, next) => {
    const { htmlContent, variables = [], description } = req.body;

    if (!htmlContent) {
        return next(new ErrorHandler('htmlContent is required', 400));
    }

    let template = await EmailTemplate.getGlobalHeader();

    if (template) {
        // Update existing
        template.htmlContent = htmlContent;
        template.variables = variables;
        template.description = description || template.description;
        template.updatedBy = req.user._id;
        template.version = (template.version || 1) + 1;
        await template.save();
    } else {
        // Create new
        template = await EmailTemplate.create({
            templateName: 'global_header_default',
            emailType: 'global_header',
            htmlContent,
            variables,
            description: description || 'Global email header template',
            category: 'global',
            isDefault: true,
            createdBy: req.user._id
        });
    }

    res.status(200).json({
        success: true,
        message: 'Global header template updated successfully',
        data: template
    });
});

/**
 * Update or create global footer template
 * PUT /api/super/email-templates/global/footer
 */
exports.updateGlobalFooter = catchAsyncErrors(async (req, res, next) => {
    const { htmlContent, variables = [], description } = req.body;

    if (!htmlContent) {
        return next(new ErrorHandler('htmlContent is required', 400));
    }

    let template = await EmailTemplate.getGlobalFooter();

    if (template) {
        // Update existing
        template.htmlContent = htmlContent;
        template.variables = variables;
        template.description = description || template.description;
        template.updatedBy = req.user._id;
        template.version = (template.version || 1) + 1;
        await template.save();
    } else {
        // Create new
        template = await EmailTemplate.create({
            templateName: 'global_footer_default',
            emailType: 'global_footer',
            htmlContent,
            variables,
            description: description || 'Global email footer template',
            category: 'global',
            isDefault: true,
            createdBy: req.user._id
        });
    }

    res.status(200).json({
        success: true,
        message: 'Global footer template updated successfully',
        data: template
    });
});

/**
 * Test send email with template
 * POST /api/super/email-templates/:id/test-send
 */
exports.testSendEmail = catchAsyncErrors(async (req, res, next) => {
    const { id } = req.params;
    const { testEmail, variables = {} } = req.body;

    if (!testEmail) {
        return next(new ErrorHandler('testEmail is required', 400));
    }

    const template = await emailTemplateService.getTemplateById(id);

    // Validate variables
    const validation = template.validateVariables(variables);
    if (!validation.valid) {
        return next(new ErrorHandler(validation.message, 400));
    }

    // Use the renderer service to get full template with header/footer
    const emailTemplateRenderer = require('../services/emailTemplateRenderer.service');
    
    try {
        const result = await emailTemplateRenderer.sendTemplateEmail(
            template.emailType,
            testEmail,
            variables
        );

        res.status(200).json({
            success: true,
            message: 'Test email sent successfully',
            data: {
                messageId: result.messageId,
                sentTo: testEmail,
                emailType: template.emailType
            }
        });
    } catch (error) {
        return next(new ErrorHandler(`Failed to send test email: ${error.message}`, 500));
    }
});