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

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

        const payroll_line_items = await db.payroll_line_items.create(
            {
                id: data.id || undefined,
        
        total_hours: data.total_hours
        ||
        null
            ,
            
        gross_pay: data.gross_pay
        ||
        null
            ,
            
        total_commission_base: data.total_commission_base
        ||
        null
            ,
            
        workers_comp_amount: data.workers_comp_amount
        ||
        null
            ,
            
        total_client_paid: data.total_client_paid
        ||
        null
            ,
            
        summary: data.summary
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await payroll_line_items.setPayroll_run( data.payroll_run || null, {
            transaction,
        });
        
        await payroll_line_items.setEmployee( data.employee || null, {
            transaction,
        });
        

        

        

        return payroll_line_items;
    }
    

    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_line_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                total_hours: item.total_hours
            ||
            null
            ,
            
                gross_pay: item.gross_pay
            ||
            null
            ,
            
                total_commission_base: item.total_commission_base
            ||
            null
            ,
            
                workers_comp_amount: item.workers_comp_amount
            ||
            null
            ,
            
                total_client_paid: item.total_client_paid
            ||
            null
            ,
            
                summary: item.summary
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return payroll_line_items;
    }

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

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


        

        const updatePayload = {};
        
        if (data.total_hours !== undefined) updatePayload.total_hours = data.total_hours;
        
        
        if (data.gross_pay !== undefined) updatePayload.gross_pay = data.gross_pay;
        
        
        if (data.total_commission_base !== undefined) updatePayload.total_commission_base = data.total_commission_base;
        
        
        if (data.workers_comp_amount !== undefined) updatePayload.workers_comp_amount = data.workers_comp_amount;
        
        
        if (data.total_client_paid !== undefined) updatePayload.total_client_paid = data.total_client_paid;
        
        
        if (data.summary !== undefined) updatePayload.summary = data.summary;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.payroll_run !== undefined) {
            await payroll_line_items.setPayroll_run(
              
              data.payroll_run,
              
              { transaction }
            );
        }
        
        if (data.employee !== undefined) {
            await payroll_line_items.setEmployee(
              
              data.employee,
              
              { transaction }
            );
        }
        

        
        

        

        return payroll_line_items;
    }

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

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

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


        return payroll_line_items;
    }

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

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

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

        await payroll_line_items.destroy({
            transaction
        });

        return payroll_line_items;
    }

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

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

        if (!payroll_line_items) {
            return payroll_line_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.payroll_run = await payroll_line_items.getPayroll_run({
            transaction
        });
        
        
        output.employee = await payroll_line_items.getEmployee({
            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.payroll_runs,
        as: 'payroll_run',
        
        where: filter.payroll_run ? {
          [Op.or]: [
            { id: { [Op.in]: filter.payroll_run.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.payroll_run.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : undefined,
        
      },

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



    ];

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

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

            
            

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    total_client_paid: {
                    ...where.total_client_paid,
                            [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.payroll_line_items.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(
                        'payroll_line_items',
                        'summary',
                        query,
                    ),
                ],
            };
        }

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

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

    
};