const Accounts = require('../models/AccountModel');

exports.getAccounts = async (req, res) => {
    try {
        const accounts = await Accounts.findAll({
            where: {
                user_id: req.userId
            }
        });

        const result = accounts.map(acc => {
            const plain = acc.toJSON();

            const balance = parseFloat(plain.balance || 0);
            const creditLimit = parseFloat(plain.credit_limit || 0);

            if (plain.type === 'CREDIT_CARD') {
                const remaining = Math.max(creditLimit - balance, 0);
                plain.remaining_limit = parseFloat(remaining.toFixed(2));
            } else {
                plain.remaining_limit = null;
            }

            return plain;
        });

        res.json(result);
    } catch (error) {
        console.log(error);
        res.status(500).json({ msg: "Gagal mengambil data akun" });
    }
};

exports.createAccount = async (req, res) => {
    const {name, type, balance, credit_limit} = req.body;
    try {
        await Accounts.create({
            name, type, balance,
            credit_limit: credit_limit || 0,
            user_id: req.userId
        });
        res.status(201).json({msg: "Akun Berhasil Dibuat!"});
    } catch (error) {
        console.log(error);
        res.status(500).json({msg: "Gagal membuat akun"});
    }
}

exports.updateAccount = async (req, res) => {
    try {
        const account = await Accounts.findOne({
            where: {
                id: req.params.id,
                user_id: req.userId
            }
        });
        if(!account) return res.status(404).json({msg: "Akun tidak ditemukan"});

        const {name, type, credit_limit} = req.body;
        
        await account.update({ name, type, credit_limit });
        res.json({msg: "Akun Berhasil Diupdate"});
    } catch (error) {
        console.log(error);
        res.status(500).json({msg: "Gagal update akun"});
    }
}

exports.deleteAccount = async (req, res) => {
    try {
        const account = await Accounts.findOne({
            where: {
                id: req.params.id,
                user_id: req.userId
            }
        });
        if(!account) return res.status(404).json({msg: "Akun tidak ditemukan"});

        await account.destroy();
        res.json({msg: "Akun Berhasil Dihapus"});
    } catch (error) {
        console.log(error);
        res.status(500).json({msg: "Gagal hapus akun (Mungkin masih ada data transaksi terkait)"});
    }
}