
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class Leave_balancesDBApi {
    

    
    static async create(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const leave_balances = await db.leave_balances.create(
            {
                id: data.id || undefined,
        
        year: data.year
        ||
        null
            ,
            
        openingBalance: data.openingBalance
        ||
        null
            ,
            
        earnedThisYear: data.earnedThisYear
        ||
        null
            ,
            
        usedYtd: data.usedYtd
        ||
        null
            ,
            
        forfeited: data.forfeited
        ||
        null
            ,
            
        convertedToCash: data.convertedToCash
        ||
        null
            ,
            
        currentBalance: data.currentBalance
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await leave_balances.setEmployee( data.employee || null, {
            transaction,
        });
        
        await leave_balances.setLeaveType( data.leaveType || null, {
            transaction,
        });
        

        

        

        return leave_balances;
    }
    

    static async bulkImport(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        // Prepare data - wrapping individual data transformations in a map() method
        const leave_balancesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                year: item.year
            ||
            null
            ,
            
                openingBalance: item.openingBalance
            ||
            null
            ,
            
                earnedThisYear: item.earnedThisYear
            ||
            null
            ,
            
                usedYtd: item.usedYtd
            ||
            null
            ,
            
                forfeited: item.forfeited
            ||
            null
            ,
            
                convertedToCash: item.convertedToCash
            ||
            null
            ,
            
                currentBalance: item.currentBalance
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

        // Bulk create items
        const leave_balances = await db.leave_balances.bulkCreate(leave_balancesData, { transaction });

        // For each item created, replace relation files
        

        return leave_balances;
    }

    static async update(id, data,  options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;
        

        const leave_balances = await db.leave_balances.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.year !== undefined) updatePayload.year = data.year;
        
        
        if (data.openingBalance !== undefined) updatePayload.openingBalance = data.openingBalance;
        
        
        if (data.earnedThisYear !== undefined) updatePayload.earnedThisYear = data.earnedThisYear;
        
        
        if (data.usedYtd !== undefined) updatePayload.usedYtd = data.usedYtd;
        
        
        if (data.forfeited !== undefined) updatePayload.forfeited = data.forfeited;
        
        
        if (data.convertedToCash !== undefined) updatePayload.convertedToCash = data.convertedToCash;
        
        
        if (data.currentBalance !== undefined) updatePayload.currentBalance = data.currentBalance;
        
        
        updatePayload.updatedById = currentUser.id;

        await leave_balances.update(updatePayload, {transaction});

        
        
        if (data.employee !== undefined) {
            await leave_balances.setEmployee(
              
              data.employee,
              
              { transaction }
            );
        }
        
        if (data.leaveType !== undefined) {
            await leave_balances.setLeaveType(
              
              data.leaveType,
              
              { transaction }
            );
        }
        

        
        

        

        return leave_balances;
    }

    static async deleteByIds(ids, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const leave_balances = await db.leave_balances.findAll({
            where: {
                id: {
                    [Op.in]: ids,
                },
            },
            transaction,
        });

        await db.sequelize.transaction(async (transaction) => {
            for (const record of leave_balances) {
                await record.update(
                    {deletedBy: currentUser.id},
                    {transaction}
                );
            }
            for (const record of leave_balances) {
                await record.destroy({transaction});
            }
        });


        return leave_balances;
    }

    static async remove(id, options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;

        const leave_balances = await db.leave_balances.findByPk(id, options);

        await leave_balances.update({
            deletedBy: currentUser.id
        }, {
            transaction,
        });

        await leave_balances.destroy({
            transaction
        });

        return leave_balances;
    }

    static async findBy(where, options) {
        const transaction = (options && options.transaction) || undefined;

        const leave_balances = await db.leave_balances.findOne(
            { where },
            { transaction },
        );

        if (!leave_balances) {
            return leave_balances;
        }

        const output = leave_balances.get({plain: true});

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.employee = await leave_balances.getEmployee({
            transaction
        });
        
        
        output.leaveType = await leave_balances.getLeaveType({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.employees,
        as: 'employee',
        
        where: filter.employee ? {
          [Op.or]: [
            { id: { [Op.in]: filter.employee.split('|').map(term => Utils.uuid(term)) } },
            {
              employeeCode: {
                [Op.or]: filter.employee.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.leave_types,
        as: 'leaveType',
        
        where: filter.leaveType ? {
          [Op.or]: [
            { id: { [Op.in]: filter.leaveType.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.leaveType.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

        if (filter) {
            if (filter.id) {
                where = {
                    ...where,
                    ['id']: Utils.uuid(filter.id),
                };
            }

            

            
            

            
            if (filter.yearRange) {
                const [start, end] = filter.yearRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    year: {
                    ...where.year,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    year: {
                    ...where.year,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.openingBalanceRange) {
                const [start, end] = filter.openingBalanceRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    openingBalance: {
                    ...where.openingBalance,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    openingBalance: {
                    ...where.openingBalance,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.earnedThisYearRange) {
                const [start, end] = filter.earnedThisYearRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    earnedThisYear: {
                    ...where.earnedThisYear,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    earnedThisYear: {
                    ...where.earnedThisYear,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.usedYtdRange) {
                const [start, end] = filter.usedYtdRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    usedYtd: {
                    ...where.usedYtd,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    usedYtd: {
                    ...where.usedYtd,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.forfeitedRange) {
                const [start, end] = filter.forfeitedRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    forfeited: {
                    ...where.forfeited,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    forfeited: {
                    ...where.forfeited,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.convertedToCashRange) {
                const [start, end] = filter.convertedToCashRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    convertedToCash: {
                    ...where.convertedToCash,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    convertedToCash: {
                    ...where.convertedToCash,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.currentBalanceRange) {
                const [start, end] = filter.currentBalanceRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    currentBalance: {
                    ...where.currentBalance,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    currentBalance: {
                    ...where.currentBalance,
                            [Op.lte]: end,
                    },
                };
                }
            }
            

            if (filter.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            


      

      



            if (filter.createdAtRange) {
                const [start, end] = filter.createdAtRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.gte]: start,
                        },
                    };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.lte]: end,
                        },
                    };
                }
            }
        }
        

        

        const queryOptions = {
            where,
            include,
            distinct: true,
            order: filter.field && filter.sort
                ? [[filter.field, filter.sort]]
                : [['createdAt', 'desc']],
            transaction: options?.transaction,
            logging: console.log
        };

        if (!options?.countOnly) {
            queryOptions.limit = limit ? Number(limit) : undefined;
            queryOptions.offset = offset ? Number(offset) : undefined;
        }

        try {
            const { rows, count } = await db.leave_balances.findAndCountAll(queryOptions);

            return {
                rows: options?.countOnly ? [] : rows,
                count: count
            };
        } catch (error) {
            console.error('Error executing query:', error);
            throw error;
        }
    }

    static async findAllAutocomplete(query, limit, offset, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'leave_balances',
                        'year',
                        query,
                    ),
                ],
            };
        }

        const records = await db.leave_balances.findAll({
            attributes: [ 'id', 'year' ],
            where,
            limit: limit ? Number(limit) : undefined,
            offset: offset ? Number(offset) : undefined,
            orderBy: [['year', 'ASC']],
        });

        return records.map((record) => ({
            id: record.id,
            label: record.year,
        }));
    }

    
};

