import { Request, Response } from 'express';
import db from '../../database/models/index.js';
const { DealerBankDetail, AuditLog } = db;
import { AuthRequest } from '../../types/express.types.js';
import { AUDIT_ACTIONS } from '../../common/config/constants.js';

export const getBankDetailsByDealerId = async (req: Request, res: Response) => {
    try {
        const { dealerId } = req.params;
        const bankDetails = await DealerBankDetail.findAll({
            where: { dealerId },
            order: [['isPrimary', 'DESC'], ['createdAt', 'DESC']]
        });
        res.json({ success: true, bankDetails });
    } catch (error) {
        console.error('Error fetching bank details:', error);
        res.status(500).json({ success: false, message: 'Error fetching bank details' });
    }
};

export const upsertBankDetail = async (req: AuthRequest, res: Response) => {
    try {
        const { dealerId } = req.params;
        const { id, accountHolderName, accountNumber, ifscCode, bankName, branchName, isPrimary } = req.body;

        if (isPrimary) {
            // Set others as non-primary
            await DealerBankDetail.update(
                { isPrimary: false },
                { where: { dealerId } }
            );
        }

        let bankDetail;
        if (id) {
            bankDetail = await DealerBankDetail.findByPk(id);
            if (!bankDetail) return res.status(404).json({ success: false, message: 'Bank detail not found' });
            
            await bankDetail.update({
                accountHolderName, accountNumber, ifscCode, bankName, branchName, isPrimary
            });
            
            await AuditLog.create({
                userId: req.user?.id || null,
                action: AUDIT_ACTIONS.UPDATED,
                entityType: 'dealer_bank',
                entityId: id,
                newData: { accountHolderName, bankName, isPrimary }
            });
        } else {
            bankDetail = await DealerBankDetail.create({
                dealerId, accountHolderName, accountNumber, ifscCode, bankName, branchName, isPrimary
            });
            
            await AuditLog.create({
                userId: req.user?.id || null,
                action: AUDIT_ACTIONS.CREATED,
                entityType: 'dealer_bank',
                entityId: bankDetail.id,
                newData: { accountHolderName, bankName, isPrimary }
            });
        }

        res.json({ success: true, message: 'Bank detail saved successfully', bankDetail });
    } catch (error) {
        console.error('Error saving bank detail:', error);
        res.status(500).json({ success: false, message: 'Error saving bank detail' });
    }
};

export const deleteBankDetail = async (req: AuthRequest, res: Response) => {
    try {
        const { id } = req.params;
        const bankDetail = await DealerBankDetail.findByPk(id);
        if (!bankDetail) return res.status(404).json({ success: false, message: 'Bank detail not found' });

        await bankDetail.destroy();
        
        await AuditLog.create({
            userId: req.user?.id || null,
            action: AUDIT_ACTIONS.DELETED,
            entityType: 'dealer_bank',
            entityId: id
        });

        res.json({ success: true, message: 'Bank detail deleted successfully' });
    } catch (error) {
        console.error('Error deleting bank detail:', error);
        res.status(500).json({ success: false, message: 'Error deleting bank detail' });
    }
};
