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

class PEntity extends Model {

    static associate(models) {

        PEntity.belongsToMany(models.User, {
            through: "user_p_entity"
        });

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

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

        PEntity.belongsTo(models.Entity, {
            as: "entity",
            foreignKey: "ent_id"
        });

        PEntity.hasMany(models.InvoiceTemplate, {
            as: "payee",
            foreignKey: "payee_id"
        });
    }

    async createPEntity(data, creatorId) {
        try {
            const pentity = await PEntity.create({...data, creatorId});
            console.log(pentity.toJSON());
            return pentity.toJSON();
        }
        catch (err) {
            console.log(err);
            return err;
        }
    }

    async getPEntity(id) {
        try {
            const pentity = await PEntity.findAll(
                {
                    include: [
                        {
                            model: Entity,
                            as: "entity",
                            where: {
                                id: id
                            },
                            attributes: []
                        }
                    ],
                    attributes: ["id", "name"]
                }
            );
            console.log(pentity.map(p => p.toJSON()));
            return pentity.map(p => p.toJSON());
        }
        catch (err) {
            console.log(err);
            return err;
        }
    }
    
    async readPEntity(ordCol, ordDir, offsetVal, limitVal, id, searchTerm) {
        try {
            const [safeOrderCol, safeOrderDir] = sanitizeSort(ordCol, ordDir, [
                'id', 'name', 'nickname', 'type', 'description', 'pan', 'gst', 'tax_details', 'address', 'contact_no', 'email', 'status', 'ent_id', 'creatorId', 'createdAt', 'updatedAt'
            ]);
            const { safeOffset, safeLimit } = sanitizePagination(offsetVal, limitVal);
            const pentity = await PEntity.findAll(
                {
                    where: searchTerm
                        ? {
                            [Op.or]: [
                                {name: {[Op.like]: `%${searchTerm}%`}},
                                {nickname: {[Op.like]: `%${searchTerm}%`}},
                            ]
                        }
                    : {},
                    include: [
                        {
                            model: Entity,
                            as: "entity",
                            where: {
                                id: id  
                            },
                            attributes: []
                        }
                    ],
                    order: [[safeOrderCol, safeOrderDir]],
                    offset: safeOffset,
                    limit: safeLimit
                }
            );
            console.log(pentity);
            return pentity;
        }
        catch (err) {
            console.log(err);
            return err;
        }
    }

    async readPEntityRow(data) {
        try {
            const pentity = await PEntity.findOne(
                {
                    where: {
                        id: data.id
                    }
                }
            )
            console.log(pentity.toJSON());
            return pentity.toJSON();
        }
        catch (err) {
            console.log(err);
            return err;
        }
    } 

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

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

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

    async countPEntity(id) {
        try {
            const count = await PEntity.count(
                {
                    include: [
                        {
                            model: Entity,
                            as: "entity",
                            where: {
                                id: id  
                            },
                        }
                    ]
            }
            );
            console.log(count);
            return count;
        }
        catch (err) {
            console.log(err);
            return err;
        }
    }
}

PEntity.init(
    {
        name: {
            type: DataTypes.STRING(100),
            allowNull: false
        },
        nickname: {
            type: DataTypes.STRING(25),
            allowNull: false
        },
        type: {
            type: DataTypes.STRING(25),
            allowNull: false
        },
        description: {
            type: DataTypes.TEXT,
            allowNull: true
        },
        pan: {
            type: DataTypes.STRING(25),
            allowNull: true
        },
        gst: {
            type: DataTypes.STRING(25),
            allowNull: true
        },
        tax_details: {
            type: DataTypes.JSON,
            allowNull: false
        },
        address: {
            type: DataTypes.STRING(250),
            allowNull: false
        },
        contact_no: {
            type: DataTypes.STRING(25),
            allowNull: false
        },
        email: {
            type: DataTypes.STRING(50),
            allowNull: false
        },
        status: {
            type: DataTypes.STRING(25),
            allowNull: false
        },
        ent_id: {
            type: DataTypes.INTEGER,
            allowNull: true,
            references: {
                model: 'entity',
                key: 'id'
            }
        },
        creatorId: {
            type: DataTypes.INTEGER,
            allowNull: false
        }
    },
    {
        sequelize,
        modelName: "PEntity",
        tableName: "p_entity"
    }
)

module.exports = PEntity;