const { Model, DataTypes, Op } = require('sequelize');
const sequelize = require('../config/db.js');
const Bank = require('./bank.js');
const BankBranch = require('./bank_branch.js');
const { sanitizeSort, sanitizePagination } = require('./querySafety.js');

class BankAccount extends Model {

    static associate(models) {

        BankAccount.belongsToMany(models.Entity, { 
            through: "entity_accounts"
        });

        BankAccount.belongsTo(models.BankBranch, { 
            as: "bank_branch", 
            foreignKey: "branch_id"
        });

        BankAccount.belongsTo(models.Bank, {
            as: "bank", 
            foreignKey: "bank_id"
        });

        BankAccount.belongsToMany(models.PEntity, { 
            through: "p_entity_accounts"
        });

        BankAccount.hasMany(models.InvoiceTemplate, {
            as: "invoice_templates",
            foreignKey: "acc_id"
        });
    }

    async createAccount(data, creatorId) {
        try {
            const account = await BankAccount.create({...data, creatorId});
            console.log(account.toJSON());
            return account.toJSON();
        }
        catch (err) {
            console.log(err);
            return err;
        }
    }

    async readAccountNames(id) {
        try {
            const account = await BankAccount.findAll(
                {
                    where: {
                        ent_id: id
                    },
                    attributes: ["id", "name", "account_no"],
                    include: [
                        {
                            model: BankBranch,
                            as: "bank_branch",
                            attributes: ["id", "name", "ifsc"],
                            include: [
                                {
                                    model: Bank,
                                    as: "bank",
                                    attributes: ["id", "name"]
                                }
                            ]
                        }
                    ],
                    raw: true,
                    nest: false
                }
            );
            console.log(account);
            return account;
        }
        catch (err) {
            console.log(err);
            return err;
        }
    }
    
    async readAccount(ordCol, ordDir, offsetVal, limitVal, searchTerm) {
        try {
            const [safeOrderCol, safeOrderDir] = sanitizeSort(ordCol, ordDir, [
                'id', 'name', 'nickname', 'type', 'description', 'branch_id', 'ent_id', 'account_no', 'status', 'creatorId', 'createdAt', 'updatedAt'
            ]);
            const { safeOffset, safeLimit } = sanitizePagination(offsetVal, limitVal);
            const account = await BankAccount.findAll(
                {
                    where: searchTerm
                        ? {
                            [Op.or]: [
                                {name: {[Op.like]: `%${searchTerm}%`}},
                                {nickname: {[Op.like]: `%${searchTerm}%`}},
                            ]
                        }
                    : {},
                    order: [[safeOrderCol, safeOrderDir]],
                    offset: safeOffset,
                    limit: safeLimit,
                    include: [
                        {
                            model: BankBranch,
                            as: "bank_branch",
                            attributes: ["id", "name", "ifsc"],
                            include: [
                                {
                                    model: Bank,
                                    as: "bank",
                                    attributes: ["id", "name"]
                                }
                            ]
                        }
                    ],
                    raw: true,
                    nest: false
                }
            );
            // console.log(account.map(a => a.toJSON()));
            return account;
        }
        catch (err) {
            console.log(err);
            return err;
        }
    }

    async readAccountRow(data) {
        try {
            const account = await BankAccount.findOne(
                {
                    where: {
                        id: data.id
                    }
                }
            )
            console.log(account.toJSON());
            return account.toJSON();
        }
        catch (err) {
            console.log(err);
            return err;
        }
    } 

    async updateAccount(data) {
        try {
            const result = await BankAccount.update(data, {where: {id: data.id}});
            console.log(`Bank Account with ${data.id} updated`, result[0]);
            return result[0];
        }
        catch (err) {
            console.log(err);
            return err;
        }
    }

    async deleteAccount(data) {
        try {
            const result = await BankAccount.destroy(
                {
                    where: {id: data.id}
                }
            );

            if (result) {
                console.log(`Account ${data.id} deleted`);
                return result;
            }
            else {
                console.log(`Account ${data.id} not found`);
                return `Account ${data.id} not found`;
            }
        }
        catch (err) {
            console.log(err);
            return err;
        }
    }

    async countAccounts() {
        try {
            const count = await BankAccount.count();
            console.log(count);
            return count;
        }
        catch (err) {
            console.log(err);
            return err;
        }
    }
}

BankAccount.init(
    {
        name: {
            type: DataTypes.STRING(100),
            allowNull: false
        },
        nickname: {
            type: DataTypes.STRING(50),
            allowNull: false
        },
        type: {
            type: DataTypes.STRING(50),
            allowNull: false
        },
        description: {
            type: DataTypes.TEXT,
            allowNull: true
        },
        branch_id: {
            type: DataTypes.INTEGER,
            allowNull: false,
            references: {
                model: 'bank_branch',
                key: 'id'
            }
        },
        ent_id: {
            type: DataTypes.INTEGER,
            allowNull: false,
            references: {
                model: 'entity',
                key: 'id'
            }
        },
        account_no: {
            type: DataTypes.STRING(50),
            allowNull: false
        },
        status: {
            type: DataTypes.STRING(25),
            allowNull: false
        },
        creatorId: {
            type: DataTypes.INTEGER,
            allowNull: false
        }
    },
    {
        sequelize,
        modelName: "BankAccount",
        tableName: "bank_accounts"
    }
)

module.exports = BankAccount;