import { Response, NextFunction } from 'express';
import { Op } from 'sequelize';
import db from '../../database/models/index.js';
import logger from '../../common/utils/logger.js';
import {
    TERMINATION_STAGES,
    AUDIT_ACTIONS,
    ROLES,
    TERMINATION_DOCUMENT_TYPES,
    TERMINATION_DOCUMENT_STAGES
} from '../../common/config/constants.js';
import { Transaction } from 'sequelize';
import { AuthRequest } from '../../types/express.types.js';
import ExternalMocksService from '../../common/utils/externalMocks.service.js';

import { TerminationWorkflowService } from '../../services/TerminationWorkflowService.js';
import { NomenclatureService } from '../../common/utils/nomenclature.js';
import { ParticipantService } from '../../services/ParticipantService.js';
import { getTerminationStatusForStage, normalizeClearanceStatus } from '../../common/utils/offboardingStatus.js';
import { resolveEntityUuidByType } from '../../common/utils/requestResolver.js';
import { OFFBOARDING_ACTIONS, REQUEST_TYPES } from '../../common/config/constants.js';
import { validateOffboardingAction, getPreviousStage } from '../../common/utils/offboardingWorkflow.utils.js';

const resolveTerminationUuid = async (id: string) => {
    const { resolvedId } = await resolveEntityUuidByType(db as any, id, 'termination');
    return resolvedId;
};

// Create termination request
export const createTermination = async (req: AuthRequest, res: Response, next: NextFunction) => {
    const transaction: Transaction = await db.sequelize.transaction();
    try {
        if (!req.user) throw new Error('Unauthorized');
        const { dealerId, category, reason, proposedLwd, comments } = req.body;

        const requestId = await NomenclatureService.generateTerminationId();
        const termination = await db.TerminationRequest.create({
            requestId,
            dealerId,
            category,
            reason,
            proposedLwd,
            comments,
            initiatedBy: req.user.id,
            currentStage: TERMINATION_STAGES.RBM_REVIEW,
            status: getTerminationStatusForStage(TERMINATION_STAGES.RBM_REVIEW),
            progressPercentage: TerminationWorkflowService.calculateProgress(TERMINATION_STAGES.RBM_REVIEW),
            timeline: [{
                stage: 'Submitted',
                targetStage: TERMINATION_STAGES.RBM_REVIEW,
                timestamp: new Date(),
                user: req.user.fullName,
                action: `Termination request initiated and forwarded to ${TERMINATION_STAGES.RBM_REVIEW}`,
                remarks: comments
            }]
        }, { transaction });

        await db.TerminationAudit.create({
            userId: req.user.id,
            action: AUDIT_ACTIONS.CREATED,
            terminationRequestId: termination.id,
            remarks: 'Admin initiated termination request'
        }, { transaction });

        await transaction.commit();

        // Add as chat participants (Async)
        ParticipantService.assignTerminationParticipants(termination.id)
            .catch(err => logger.error('Error assigning participants to termination:', err));

        res.status(201).json({ success: true, message: 'Termination request created', termination });
    } catch (error) {
        if (transaction) await transaction.rollback();
        logger.error('Error creating termination:', error);
        next(error);
    }
};

// Get all termination requests
export const getTerminations = async (req: AuthRequest, res: Response, next: NextFunction) => {
    try {
        if (!req.user) throw new Error('Unauthorized');
        const { dealerId } = req.query;
        const where: any = {};
        
        if (dealerId) where.dealerId = dealerId;
        if (req.user.roleCode === ROLES.DEALER) {
            const dealer = await db.Dealer.findOne({ where: { userId: req.user.id } });
            if (dealer) where.dealerId = dealer.id;
        } else {
            const { status } = req.query;
            if (status) {
                if (status === 'open') {
                    where.status = { [Op.notIn]: ['Terminated', 'Completed', 'Closed', 'Rejected'] };
                } else if (status === 'completed') {
                    where.status = { [Op.in]: ['Terminated', 'Completed', 'Closed'] };
                } else {
                    where.status = status;
                }
            }
        }

        const page = parseInt(req.query.page as string) || 1;
        const limit = parseInt(req.query.limit as string) || 10;
        const offset = (page - 1) * limit;

        const { count, rows: terminations } = await db.TerminationRequest.findAndCountAll({
            where,
            include: [
                { 
                    model: db.Dealer, 
                    as: 'dealer',
                    include: [{ model: db.DealerCode, as: 'dealerCode' }]
                }
            ],
            order: [['createdAt', 'DESC']],
            limit,
            offset,
            distinct: true
        });
        res.json({ 
            success: true, 
            terminations,
            meta: {
                total: count,
                totalPages: Math.ceil(count / limit),
                currentPage: page,
                limit,
                stats: {
                    total: count,
                    open: await db.TerminationRequest.count({ where: { ...where, status: { [Op.notIn]: ['Terminated', 'Completed', 'Closed', 'Rejected'] } } }),
                    completed: await db.TerminationRequest.count({ where: { ...where, status: { [Op.in]: ['Terminated', 'Completed', 'Closed'] } } })
                }
            }
        });
    } catch (error) {
        logger.error('Error fetching terminations:', error);
        next(error);
    }
};

// Get termination request by ID
export const getTerminationById = async (req: AuthRequest, res: Response, next: NextFunction) => {
    try {
        const { id } = req.params;
        const resolvedId = await resolveTerminationUuid(String(id));

        const termination = await db.TerminationRequest.findOne({
            where: { id: resolvedId },
            include: [
                { 
                    model: db.Dealer, 
                    as: 'dealer',
                    include: [
                        { 
                            model: db.Application, 
                            as: 'application',
                            include: [
                                { model: db.District, as: 'district' },
                                { 
                                    model: db.LoiRequest, 
                                    as: 'loiRequests',
                                    where: { status: 'approved' },
                                    required: false
                                },
                                { 
                                    model: db.LoaRequest, 
                                    as: 'loaRequests',
                                    where: { status: 'approved' },
                                    required: false
                                }
                            ]
                        },
                        { model: db.DealerCode, as: 'dealerCode' },
                        { model: db.User, as: 'user', attributes: ['id', 'email', 'mobileNumber', 'status'] }
                    ]
                },
                { model: db.User, as: 'initiator', attributes: ['id', 'fullName', 'email'] },
                { 
                    model: db.TerminationDocument, 
                    as: 'uploadedDocuments',
                    include: [{ model: db.User, as: 'uploader', attributes: ['fullName'] }]
                },
                { model: db.FnF, as: 'fnfSettlement' },
                { 
                    model: db.RequestParticipant, 
                    as: 'participants',
                    include: [{ model: db.User, as: 'user', attributes: ['id', 'fullName', 'email', 'roleCode'] }]
                }
            ]
        });

        if (!termination) {
            return res.status(404).json({ success: false, message: 'Termination request not found' });
        }
        res.json({ success: true, termination });
    } catch (error) {
        logger.error('Error fetching termination:', error);
        next(error);
    }
};

export const uploadTerminationDocument = async (req: AuthRequest, res: Response, next: NextFunction) => {
    const transaction: Transaction = await db.sequelize.transaction();
    try {
        if (!req.user) throw new Error('Unauthorized');
        const { id } = req.params;
        const { documentType = TERMINATION_DOCUMENT_TYPES[0], stage = null } = req.body;

        if (!req.file) {
            await transaction.rollback();
            return res.status(400).json({ success: false, message: 'File is required' });
        }

        if (!TERMINATION_DOCUMENT_TYPES.includes(documentType)) {
            await transaction.rollback();
            return res.status(400).json({
                success: false,
                message: `Invalid document type. Allowed values: ${TERMINATION_DOCUMENT_TYPES.join(', ')}`
            });
        }
        if (stage && !TERMINATION_DOCUMENT_STAGES.includes(stage)) {
            await transaction.rollback();
            return res.status(400).json({
                success: false,
                message: `Invalid stage. Allowed values: ${TERMINATION_DOCUMENT_STAGES.join(', ')}`
            });
        }
        const resolvedId = await resolveTerminationUuid(String(id));
        const termination = await db.TerminationRequest.findOne({
            where: { id: resolvedId }
        });

        if (!termination) {
            await transaction.rollback();
            return res.status(404).json({ success: false, message: 'Termination request not found' });
        }

        const filePath = `/uploads/documents/${req.file.filename}`;
        const document = await db.TerminationDocument.create({
            terminationRequestId: termination.id,
            documentType,
            fileName: req.file.originalname,
            filePath,
            fileSize: req.file.size,
            mimeType: req.file.mimetype,
            stage,
            uploadedBy: req.user.id
        }, { transaction });

        await db.TerminationAudit.create({
            userId: req.user.id,
            terminationRequestId: termination.id,
            action: AUDIT_ACTIONS.DOCUMENT_UPLOADED,
            remarks: `${documentType} uploaded`,
            details: { fileName: req.file.originalname, stage, documentType }
        }, { transaction });

        const timeline = [...(termination.timeline || []), {
            stage: termination.currentStage,
            timestamp: new Date(),
            user: req.user.fullName,
            action: `Document uploaded: ${documentType}`,
            remarks: req.file.originalname
        }];
        await termination.update({ timeline }, { transaction });

        const normalizedStage = String(stage || '').trim().toLowerCase();
        const isScnStageUpload = normalizedStage === 'show cause notice' || normalizedStage === 'show cause notice (scn)' || normalizedStage === 'scn';
        const isScnResponseDoc = String(documentType || '').trim().toLowerCase() === 'scn response';
        if (
            termination.currentStage === TERMINATION_STAGES.SCN_ISSUED &&
            (isScnStageUpload || isScnResponseDoc)
        ) {
            await TerminationWorkflowService.handleScnResponse(termination, {
                responseBody: `SCN response uploaded: ${req.file.originalname}`,
                documents: [{ fileName: req.file.originalname, filePath }]
            }, req.user.id);
        }

        await transaction.commit();
        res.status(201).json({ success: true, message: 'Document uploaded successfully', document });
    } catch (error) {
        await transaction.rollback();
        logger.error('Error uploading termination document:', error);
        next(error);
    }
};

// Update termination status (Approve/Reject)
export const updateTerminationStatus = async (req: AuthRequest, res: Response, next: NextFunction) => {
    const transaction: Transaction = await db.sequelize.transaction();
    try {
        if (!req.user) throw new Error('Unauthorized');
        const { id } = req.params;
        const { action, remarks } = req.body;
        const resolvedId = await resolveTerminationUuid(String(id));

        const termination = await db.TerminationRequest.findByPk(resolvedId);
        if (!termination) {
            await transaction.rollback();
            return res.status(404).json({ success: false, message: 'Termination not found' });
        }

        const fromStage = termination.currentStage;
        let approvedToStage: string | null = null;

        if (action === OFFBOARDING_ACTIONS.REJECT) {
            await TerminationWorkflowService.transitionTermination(termination, TERMINATION_STAGES.REJECTED, req.user.id, {
                action: 'Rejected',
                status: 'Rejected',
                remarks
            });
        } else if (action === OFFBOARDING_ACTIONS.REVOKE) {
            // Validation: Remarks mandatory for Revoke
            const validation = validateOffboardingAction(action, remarks);
            if (!validation.valid) {
                await transaction.rollback();
                return res.status(400).json({ success: false, message: validation.message });
            }

            await TerminationWorkflowService.transitionTermination(termination, TERMINATION_STAGES.REJECTED, req.user.id, {
                action: 'Revoked',
                status: 'Revoked',
                remarks
            });
        } else if (action === OFFBOARDING_ACTIONS.SEND_BACK || action === 'sendback') {
            // Validation: Remarks mandatory for Send Back
            const validation = validateOffboardingAction(OFFBOARDING_ACTIONS.SEND_BACK, remarks);
            if (!validation.valid) {
                await transaction.rollback();
                return res.status(400).json({ success: false, message: validation.message });
            }

            const previousStage = getPreviousStage(REQUEST_TYPES.TERMINATION, termination.currentStage);
            if (!previousStage) {
                await transaction.rollback();
                return res.status(400).json({ success: false, message: 'Cannot send back from current stage' });
            }

            await TerminationWorkflowService.transitionTermination(termination, previousStage, req.user.id, {
                action: 'Sent Back',
                remarks
            });
        } else if (action === 'pushfnf') {
            if (termination.currentStage !== TERMINATION_STAGES.TERMINATED && termination.currentStage !== TERMINATION_STAGES.LEGAL_LETTER) {
                await transaction.rollback();
                return res.status(400).json({
                    success: false, 
                    message: `Cannot trigger F&F from ${termination.currentStage}. Complete the CEO and Legal approvals first.`
                });
            }

            logger.info(`[TerminationController] Forcibly initiating F&F (pushfnf) for Termination ${termination.requestId}`);
            await TerminationWorkflowService.initiateFnF(termination, req.user.id, transaction);
            
            // Maintain timeline visibility
            const timeline = [...(termination.timeline || []), {
                stage: termination.currentStage,
                timestamp: new Date(),
                user: req.user.fullName,
                action: 'Forced F&F Initiation',
                remarks: remarks || 'F&F settlement initiated manually via Push to F&F'
            }];
            await termination.update({ 
                currentStage: TERMINATION_STAGES.TERMINATED, // Lock out further approvals
                status: 'F&F Initiated', 
                timeline 
            }, { transaction });
        } else {
            const stageFlow: Record<string, string> = {
                [TERMINATION_STAGES.SUBMITTED]: TERMINATION_STAGES.RBM_REVIEW,
                [TERMINATION_STAGES.RBM_REVIEW]: TERMINATION_STAGES.ZBH_REVIEW,
                [TERMINATION_STAGES.ZBH_REVIEW]: TERMINATION_STAGES.DD_LEAD_REVIEW,
                [TERMINATION_STAGES.DD_LEAD_REVIEW]: TERMINATION_STAGES.LEGAL_VERIFICATION,
                [TERMINATION_STAGES.LEGAL_VERIFICATION]: TERMINATION_STAGES.DD_HEAD_REVIEW,
                [TERMINATION_STAGES.DD_HEAD_REVIEW]: TERMINATION_STAGES.NBH_EVALUATION,
                [TERMINATION_STAGES.NBH_EVALUATION]: TERMINATION_STAGES.SCN_ISSUED,
                [TERMINATION_STAGES.SCN_ISSUED]: TERMINATION_STAGES.PERSONAL_HEARING,
                [TERMINATION_STAGES.PERSONAL_HEARING]: TERMINATION_STAGES.NBH_FINAL_APPROVAL,
                [TERMINATION_STAGES.NBH_FINAL_APPROVAL]: TERMINATION_STAGES.CCO_APPROVAL,
                [TERMINATION_STAGES.CCO_APPROVAL]: TERMINATION_STAGES.CEO_APPROVAL,
                [TERMINATION_STAGES.CEO_APPROVAL]: TERMINATION_STAGES.LEGAL_LETTER,
                [TERMINATION_STAGES.LEGAL_LETTER]: TERMINATION_STAGES.TERMINATED
            };

            const nextStage = stageFlow[termination.currentStage];
            logger.info(`[TerminationController] transitioning from ${termination.currentStage} to ${nextStage}`);
            if (!nextStage) {
                await transaction.rollback();
                return res.status(400).json({ success: false, message: 'Cannot approve from current stage' });
            }

            approvedToStage = nextStage;

            await TerminationWorkflowService.transitionTermination(termination, nextStage, req.user.id, {
                remarks,
                status: getTerminationStatusForStage(nextStage)
            });

            // If Terminated, trigger F&F initiation via Workflow Service
            // SRS REQUIREMENT: F&F settlement process is triggered only on the Last Working Day (LWD)
            if (nextStage === TERMINATION_STAGES.TERMINATED) {
                const today = new Date();
                const lwd = new Date(termination.proposedLwd);
                
                // Clear time components for date-only comparison
                today.setHours(0, 0, 0, 0);
                lwd.setHours(0, 0, 0, 0);

                if (today >= lwd) {
                    logger.info(`[TerminationController] LWD reached or passed (${termination.proposedLwd}). Initiating F&F.`);
                    await TerminationWorkflowService.initiateFnF(termination, req.user.id, transaction);
                } else {
                    logger.info(`[TerminationController] Termination approved but LWD (${termination.proposedLwd}) not yet reached. F&F will be triggered on LWD.`);
                    // Keep parent status aligned while waiting for LWD-triggered F&F
                    await termination.update({ status: 'Awaiting F&F (LWD Pending)' }, { transaction });
                }
            }
        }

        await transaction.commit();
        res.json({ success: true, message: 'Termination updated', termination });
    } catch (error) {
        if (transaction) await transaction.rollback();
        logger.error('Error updating termination:', error);
        next(error);
    }
};



// Submit SCN Response (Dealer Principal)
export const submitScnResponse = async (req: AuthRequest, res: Response, next: NextFunction) => {
    const transaction: Transaction = await db.sequelize.transaction();
    try {
        if (!req.user) throw new Error('Unauthorized');
        const { terminationRequestId, responseBody, documents } = req.body;

        const termination = await db.TerminationRequest.findByPk(terminationRequestId);
        if (!termination) throw new Error('Termination request not found');

        const response = await TerminationWorkflowService.handleScnResponse(termination, { responseBody, documents }, req.user.id);

        await transaction.commit();
        res.status(201).json({ success: true, message: 'SCN Response submitted successfully', response });
    } catch (error) {
        if (transaction) await transaction.rollback();
        logger.error('Error submitting SCN response:', error);
        next(error);
    }
};

// Issue SCN for a specific termination request id (frontend-compatible route)
export const issueScn = async (req: AuthRequest, res: Response, next: NextFunction) => {
    const transaction: Transaction = await db.sequelize.transaction();
    try {
        if (!req.user) throw new Error('Unauthorized');
        const { id } = req.params;
        const { remarks } = req.body;
        const resolvedId = await resolveTerminationUuid(String(id));

        const termination = await db.TerminationRequest.findByPk(resolvedId);
        if (!termination) {
            await transaction.rollback();
            return res.status(404).json({ success: false, message: 'Termination request not found' });
        }

        if (termination.currentStage === TERMINATION_STAGES.NBH_EVALUATION) {
            await TerminationWorkflowService.transitionTermination(termination, TERMINATION_STAGES.SCN_ISSUED, req.user.id, {
                action: 'SCN Issued',
                status: 'Show Cause Notice',
                remarks: remarks || 'Show Cause Notice issued'
            });
        }

        await transaction.commit();
        return res.json({ success: true, message: 'SCN issued successfully', termination });
    } catch (error) {
        if (transaction) await transaction.rollback();
        logger.error('Error issuing SCN:', error);
        next(error);
    }
};

// Upload SCN response by route param id (frontend-compatible route)
export const uploadScnResponse = async (req: AuthRequest, res: Response, next: NextFunction) => {
    const transaction: Transaction = await db.sequelize.transaction();
    try {
        if (!req.user) throw new Error('Unauthorized');
        const { id } = req.params;
        const { remarks } = req.body;
        const resolvedId = await resolveTerminationUuid(String(id));

        const termination = await db.TerminationRequest.findByPk(resolvedId);
        if (!termination) {
            await transaction.rollback();
            return res.status(404).json({ success: false, message: 'Termination request not found' });
        }

        if (req.file) {
            const filePath = `/uploads/documents/${req.file.filename}`;
            await db.TerminationDocument.create({
                terminationRequestId: termination.id,
                documentType: 'SCN Response',
                fileName: req.file.originalname,
                filePath,
                fileSize: req.file.size,
                mimeType: req.file.mimetype,
                stage: TERMINATION_STAGES.SCN_ISSUED,
                uploadedBy: req.user.id
            }, { transaction });
        }

        // Move SCN -> Personal Hearing after response submission.
        if (termination.currentStage === TERMINATION_STAGES.SCN_ISSUED) {
            await TerminationWorkflowService.handleScnResponse(termination, {
                responseBody: remarks || 'SCN response uploaded via portal',
                documents: req.file ? [{ fileName: req.file.originalname }] : []
            }, req.user.id);
        }

        await transaction.commit();
        return res.status(201).json({ success: true, message: 'SCN response uploaded successfully', termination });
    } catch (error) {
        if (transaction) await transaction.rollback();
        logger.error('Error uploading SCN response:', error);
        next(error);
    }
};

// Record Personal Hearing Outcome
export const recordPersonalHearing = async (req: AuthRequest, res: Response, next: NextFunction) => {
    const transaction: Transaction = await db.sequelize.transaction();
    try {
        if (!req.user) throw new Error('Unauthorized');
        const { terminationRequestId, attendees, summary, recommendation, momDocumentId } = req.body;

        const termination = await db.TerminationRequest.findByPk(terminationRequestId);
        if (!termination) throw new Error('Termination request not found');

        const hearing = await TerminationWorkflowService.handleHearingOutcome(termination, { attendees, summary, recommendation, momDocumentId }, req.user.id);

        await transaction.commit();
        res.status(201).json({ success: true, message: 'Hearing record saved', recommendation });
    } catch (error) {
        if (transaction) await transaction.rollback();
        logger.error('Error recording hearing:', error);
        next(error);
    }
};

// Final Authorization (NBH Final / CCO / CEO)
export const finalizeTermination = async (req: AuthRequest, res: Response, next: NextFunction) => {
    const transaction: Transaction = await db.sequelize.transaction();
    try {
        if (!req.user) throw new Error('Unauthorized');
        const { id } = req.params;
        const { decision, remarks } = req.body as { decision?: 'Approve' | 'Reject' | 'Reconsider'; remarks?: string };
        const resolvedId = await resolveTerminationUuid(String(id));

        const termination = await db.TerminationRequest.findByPk(resolvedId);
        if (!termination) {
            await transaction.rollback();
            return res.status(404).json({ success: false, message: 'Termination request not found' });
        }

        const currentStage = termination.currentStage;
        const allowedFinalizeStages = [
            TERMINATION_STAGES.NBH_FINAL_APPROVAL,
            TERMINATION_STAGES.CCO_APPROVAL,
            TERMINATION_STAGES.CEO_APPROVAL
        ];
        if (!allowedFinalizeStages.includes(currentStage as any)) {
            await transaction.rollback();
            return res.status(400).json({
                success: false,
                message: `Finalize action is not allowed at stage: ${currentStage}`
            });
        }

        if (decision === 'Reject') {
            await TerminationWorkflowService.transitionTermination(termination, TERMINATION_STAGES.REJECTED, req.user.id, {
                action: 'Final Authorization Rejected',
                actionType: OFFBOARDING_ACTIONS.REJECT,
                status: 'Rejected',
                remarks: remarks || 'Rejected during final authorization'
            });
        } else if (decision === 'Reconsider' || decision === 'Send Back' as any) {
            // Standardizing Send Back / Reconsideration logic
            const validation = validateOffboardingAction(OFFBOARDING_ACTIONS.SEND_BACK, remarks || '');
            if (!validation.valid) {
                await transaction.rollback();
                return res.status(400).json({ success: false, message: validation.message });
            }

            const previousStage = getPreviousStage(REQUEST_TYPES.TERMINATION, termination.currentStage);
            const targetStage = previousStage || TERMINATION_STAGES.NBH_EVALUATION; // Fallback to NBH if manual resolve fails

            await TerminationWorkflowService.transitionTermination(termination, targetStage, req.user.id, {
                action: 'Sent for Reconsideration',
                actionType: OFFBOARDING_ACTIONS.RECONSIDER,
                status: getTerminationStatusForStage(targetStage),
                remarks: remarks || 'Sent back for reconsideration'
            });
        } else {
            const approveFlow: Record<string, string> = {
                [TERMINATION_STAGES.NBH_FINAL_APPROVAL]: TERMINATION_STAGES.CCO_APPROVAL,
                [TERMINATION_STAGES.CCO_APPROVAL]: TERMINATION_STAGES.CEO_APPROVAL,
                [TERMINATION_STAGES.CEO_APPROVAL]: TERMINATION_STAGES.LEGAL_LETTER
            };
            const targetStage = approveFlow[currentStage];
            await TerminationWorkflowService.transitionTermination(termination, targetStage, req.user.id, {
                action: `Final Authorization Approved to ${targetStage}`,
                actionType: OFFBOARDING_ACTIONS.APPROVE,
                status: getTerminationStatusForStage(targetStage),
                remarks: remarks || 'Approved'
            });
        }

        await transaction.commit();
        return res.json({ success: true, message: 'Final authorization processed', termination });
    } catch (error) {
        if (transaction) await transaction.rollback();
        logger.error('Error finalizing termination:', error);
        next(error);
    }
};

// Record Clearance from Departments (16-Department F&F)
export const updateClearance = async (req: AuthRequest, res: Response, next: NextFunction) => {
    const transaction: Transaction = await db.sequelize.transaction();
    try {
        if (!req.user) throw new Error('Unauthorized');
        const { id } = req.params;
        const { department, status, amount, type, remarks } = req.body;
        const resolvedId = await resolveTerminationUuid(String(id));

        const termination = await db.TerminationRequest.findByPk(resolvedId);
        if (!termination) throw new Error('Termination request not found');

        const clearances = { ...(termination.departmentalClearances || {}) };
        const normalizedStatus = normalizeClearanceStatus(status, Number(amount) || 0);
        clearances[department] = {
            status: normalizedStatus,
            amount: Number(amount) || 0,
            type: type || 'Receivable',
            remarks: remarks || '',
            updatedAt: new Date().toISOString(),
            updatedBy: req.user.fullName
        };

        await termination.update({ departmentalClearances: clearances }, { transaction });

        // Update individual clearance record for unified dashboard
        const fnf = await db.FnF.findOne({ where: { terminationRequestId: resolvedId } });
        if (fnf) {
            await db.FffClearance.update(
                { status: normalizedStatus, remarks, amount: Number(amount) || 0 },
                { where: { fnfId: fnf.id, department }, transaction }
            );
        }

        await db.TerminationAudit.create({
            userId: req.user.id,
            action: 'CLEARANCE_UPDATED',
            terminationRequestId: resolvedId,
            remarks: remarks || `Cleared ${department}`,
            details: { department, status: normalizedStatus, amount }
        }, { transaction });

        if (fnf) {
            await db.FnFAudit.create({
                userId: req.user.id,
                fnfId: fnf.id,
                action: 'CLEARANCE_UPDATED',
                remarks: remarks || `Departmental clearance recorded for ${department}`,
                details: { department, status: normalizedStatus, source: 'Termination Workflow' }
            }, { transaction });
        }

        await transaction.commit();
        res.json({ success: true, message: `Clearance updated for ${department}`, clearances });
    } catch (error) {
        if (transaction) await transaction.rollback();
        logger.error('Error updating termination clearance:', error);
        next(error);
    }
};

