
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 Payroll_runsDBApi {
    

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

        const payroll_runs = await db.payroll_runs.create(
            {
                id: data.id || undefined,
        
        payroll_name: data.payroll_name
        ||
        null
            ,
            
        period_start: data.period_start
        ||
        null
            ,
            
        period_end: data.period_end
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        paid_at: data.paid_at
        ||
        null
            ,
            
        total_gross: data.total_gross
        ||
        null
            ,
            
        total_deductions: data.total_deductions
        ||
        null
            ,
            
        total_net: data.total_net
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await payroll_runs.setBranch( data.branch || null, {
            transaction,
        });
        
        await payroll_runs.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return payroll_runs;
    }
    

    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 payroll_runsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                payroll_name: item.payroll_name
            ||
            null
            ,
            
                period_start: item.period_start
            ||
            null
            ,
            
                period_end: item.period_end
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                paid_at: item.paid_at
            ||
            null
            ,
            
                total_gross: item.total_gross
            ||
            null
            ,
            
                total_deductions: item.total_deductions
            ||
            null
            ,
            
                total_net: item.total_net
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return payroll_runs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.payroll_name !== undefined) updatePayload.payroll_name = data.payroll_name;
        
        
        if (data.period_start !== undefined) updatePayload.period_start = data.period_start;
        
        
        if (data.period_end !== undefined) updatePayload.period_end = data.period_end;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.paid_at !== undefined) updatePayload.paid_at = data.paid_at;
        
        
        if (data.total_gross !== undefined) updatePayload.total_gross = data.total_gross;
        
        
        if (data.total_deductions !== undefined) updatePayload.total_deductions = data.total_deductions;
        
        
        if (data.total_net !== undefined) updatePayload.total_net = data.total_net;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.branch !== undefined) {
            await payroll_runs.setBranch(
              
              data.branch,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await payroll_runs.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return payroll_runs;
    }

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

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

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


        return payroll_runs;
    }

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

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

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

        await payroll_runs.destroy({
            transaction
        });

        return payroll_runs;
    }

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

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

        if (!payroll_runs) {
            return payroll_runs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.payroll_items_payroll_run = await payroll_runs.getPayroll_items_payroll_run({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        output.branch = await payroll_runs.getBranch({
            transaction
        });
        
        
        output.organizations = await payroll_runs.getOrganizations({
            transaction
        });
        
        

        return output;
    }

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

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.payroll_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'payroll_runs',
                        'payroll_name',
                        filter.payroll_name,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.payroll_runs.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

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

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

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

    
};

