const express = require('express');
const router = express.Router();
const authorize = require('../../../../middlewares/authorize-sapps');
const historyEmailService = require('./historyEmail.service');

router.post('/', authorize(), getAll);
router.post('/resend/:id', authorize(), resend);

module.exports = router;

function getAll(req, res, next) {
    historyEmailService.getAll(req.body)
        .then(result => {
            // Ensure consistent response format
            if (!result || typeof result !== 'object') {
                return res.json({
                    success: false,
                    message: "Invalid response from service",
                    code: "SERVICE_ERROR",
                    historyEmails: [],
                    totalCount: 0,
                    pageIndex: 0,
                    pageSize: 25
                });
            }
            res.json(result);
        })
        .catch(error => {
            console.error('Error in getAll history emails controller:', error);
            res.json({
                success: false,
                message: error?.message || "Failed to fetch history emails",
                code: error?.code || "UNKNOWN_ERROR",
                historyEmails: [],
                totalCount: 0,
                pageIndex: req.body?.pageIndex || 0,
                pageSize: req.body?.pageSize || 25
            });
        });
}

function resend(req, res, next) {
    try {
        const historyEmailId = parseInt(req.params.id);
        
        // Validate historyEmailId
        if (!historyEmailId || isNaN(historyEmailId) || historyEmailId <= 0) {
            return res.json({
                success: false,
                message: "Invalid history email ID",
                code: "INVALID_ID"
            });
        }
        
        // Get user ID from request (set by authorize middleware)
        const userId = req.user?.id || req.user?.user_id || req.body.modified_by;
        
        if (!userId) {
            return res.json({
                success: false,
                message: "User ID is required for resending email",
                code: "MISSING_USER_ID"
            });
        }
        
        const params = {
            ...req.body,
            modified_by: userId,
            owner: userId
        };
        
        historyEmailService.resend(historyEmailId, params)
            .then(result => {
                // Ensure consistent response format
                if (!result || typeof result !== 'object') {
                    return res.json({
                        success: false,
                        message: "Invalid response from service",
                        code: "SERVICE_ERROR"
                    });
                }
                res.json(result);
            })
            .catch(error => {
                console.error('Error in resend history email controller:', error);
                res.json({
                    success: false,
                    message: error?.message || "Failed to resend email",
                    code: error?.code || "UNKNOWN_ERROR"
                });
            });
    } catch (error) {
        console.error('Error in resend controller (outer catch):', error);
        res.json({
            success: false,
            message: error?.message || "Failed to process resend request",
            code: "UNKNOWN_ERROR"
        });
    }
}
