const { Model, DataTypes, Op } = require('sequelize');
const sequelize = require('../config/db.js');
const Entity = require('./entity.js');
const { sanitizeSort, sanitizePagination } = require('./querySafety.js');

class Bank extends Model {

    static associate(models) {

        Bank.hasMany(models.BankBranch, {
            as: "bank_branch",
            foreignKey: "bank_id"
        });

        Bank.hasMany(models.BankAccount, {
            as: "bank_accounts",
            foreignKey: "bank_id"
        });

        Bank.belongsToMany(models.Entity, {
            through: "entity_banks"
        });

        Bank.belongsToMany(models.PEntity, {
            through: "p_entity_banks"
        });
        
    }

    async createBank(data, creatorId) {
        try {
            const banks = await Bank.create({...data, creatorId});
            console.log(banks.toJSON());
            return banks.toJSON();
        }
        catch (err) {
            console.log(err);
            return err;
        }
    }

    async getBanksList(id) {
        try {
            const banks = await Bank.findAll(
                {
                    include: [
                        {
                            model: Entity,
                            where: {
                                id: id
                            },
                            through: {
                                attributes: []
                            },
                            attributes: []
                        }
                    ],
                    attributes: ["id", "name"]
                }
            );
            console.log(banks.map(b => b.toJSON()));
            return banks.map(b => b.toJSON());
        }
        catch(err) {
            console.log(err);
            return err;
        }
    }
    
    async readBanks(ordCol, ordDir, offsetVal, limitVal, id, searchTerm) {
        try {
            const [safeOrderCol, safeOrderDir] = sanitizeSort(ordCol, ordDir, [
                'id', 'name', 'type', 'description', 'shortcode', 'cog', 'status', 'creatorId', 'createdAt', 'updatedAt'
            ]);
            const { safeOffset, safeLimit } = sanitizePagination(offsetVal, limitVal);
            const banks = await Bank.findAll(
                {
                    where: searchTerm ? {
                        name: {
                            [Op.like]: `%${searchTerm}%`
                        }
                    } : {},
                    include: [
                        {
                            model: Entity,
                            // as: "entityBanks",
                            where: {
                                id: id
                            },
                            through: {
                                attributes: []
                            }
                        }
                    ],
                    order: [[safeOrderCol, safeOrderDir]],
                    offset: safeOffset,
                    limit: safeLimit
                }
            );
            console.log(banks.map(bank => bank.toJSON()));
            return banks.map(bank => bank.toJSON());
        }
        catch (err) {
            console.log(err);
            return err;
        }
    }

    async readBankRow(data) {
        try {
            const bank = await Bank.findOne(
                {
                    where: {
                        id: data.id
                    }
                }
            )
            console.log(bank.toJSON());
            return bank.toJSON();
        }
        catch (err) {
            console.log(err);
            return err;
        }
    } 

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

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

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

    async countBanks(id) {
        try {
            const count = await sequelize.models.entity_banks.count({
                where: {
                    entityId: id
                }
            })
            console.log(count);
            return count;
        }
        catch (err) {
            console.log(err);
            return err;
        }
    }
}

Bank.init(
    {
        name: {
            type: DataTypes.STRING(50),
            allowNull: false
        },
        type: {
            type: DataTypes.STRING(50),
            allowNull: false
        },
        description: {
            type: DataTypes.TEXT,
            allowNull: true
        },
        shortcode: {
            type: DataTypes.STRING(25),
            allowNull: false
        },
        cog: {
            type: DataTypes.STRING(50),
            allowNull: false
        },
        status: {
            type: DataTypes.STRING(25),
            allowNull: false
        },
        creatorId: {
            type: DataTypes.INTEGER,
            allowNull: false
        }
    },
    {
        sequelize,
        modelName: "Bank",
        tableName: "banks"
    }
)

module.exports = Bank;