
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,
        
        name: data.name
        ||
        null
            ,
            
        period_start: data.period_start
        ||
        null
            ,
            
        period_end: data.period_end
        ||
        null
            ,
            
        run_date: data.run_date
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { 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,
                
                name: item.name
            ||
            null
            ,
            
                period_start: item.period_start
            ||
            null
            ,
            
                period_end: item.period_end
            ||
            null
            ,
            
                run_date: item.run_date
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                notes: item.notes
            ||
            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 payroll_runs = await db.payroll_runs.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.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.run_date !== undefined) updatePayload.run_date = data.run_date;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

        await payroll_runs.update(updatePayload, {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_line_items_payroll_run = await Promise.all(
            (await payroll_runs.getPayroll_line_items_payroll_run({
                transaction
            })).map(async (payrollLineItem) => {
                const payrollLineItemOutput = payrollLineItem.get({ plain: true });

                payrollLineItemOutput.employee = await payrollLineItem.getEmployee({
                    transaction,
                });

                return payrollLineItemOutput;
            }),
        );
        
        
        

        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 = [



    ];

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

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

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            period_start: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    period_end: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

            
            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.run_dateRange) {
                const [start, end] = filter.run_dateRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    run_date: {
                    ...where.run_date,
                            [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.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_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, ) {
        let where = {};
        
        

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

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

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

    
};

