
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,
        
        periodFrom: data.periodFrom
        ||
        null
            ,
            
        periodTo: data.periodTo
        ||
        null
            ,
            
        payrollType: data.payrollType
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        lockedAt: data.lockedAt
        ||
        null
            ,
            
        computedAt: data.computedAt
        ||
        null
            ,
            
        approvedAt: data.approvedAt
        ||
        null
            ,
            
        postedAt: data.postedAt
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await payroll_runs.setApprovedByUser( data.approvedByUser || null, {
            transaction,
        });
        
        await payroll_runs.setPostedByUser( data.postedByUser || null, {
            transaction,
        });
        
        await payroll_runs.setJournalEntry( data.journalEntry || 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,
                
                periodFrom: item.periodFrom
            ||
            null
            ,
            
                periodTo: item.periodTo
            ||
            null
            ,
            
                payrollType: item.payrollType
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                lockedAt: item.lockedAt
            ||
            null
            ,
            
                computedAt: item.computedAt
            ||
            null
            ,
            
                approvedAt: item.approvedAt
            ||
            null
            ,
            
                postedAt: item.postedAt
            ||
            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.periodFrom !== undefined) updatePayload.periodFrom = data.periodFrom;
        
        
        if (data.periodTo !== undefined) updatePayload.periodTo = data.periodTo;
        
        
        if (data.payrollType !== undefined) updatePayload.payrollType = data.payrollType;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.lockedAt !== undefined) updatePayload.lockedAt = data.lockedAt;
        
        
        if (data.computedAt !== undefined) updatePayload.computedAt = data.computedAt;
        
        
        if (data.approvedAt !== undefined) updatePayload.approvedAt = data.approvedAt;
        
        
        if (data.postedAt !== undefined) updatePayload.postedAt = data.postedAt;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.approvedByUser !== undefined) {
            await payroll_runs.setApprovedByUser(
              
              data.approvedByUser,
              
              { transaction }
            );
        }
        
        if (data.postedByUser !== undefined) {
            await payroll_runs.setPostedByUser(
              
              data.postedByUser,
              
              { transaction }
            );
        }
        
        if (data.journalEntry !== undefined) {
            await payroll_runs.setJournalEntry(
              
              data.journalEntry,
              
              { 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.time_records_payrollRun = await payroll_runs.getTime_records_payrollRun({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.payroll_items_payrollRun = await payroll_runs.getPayroll_items_payrollRun({
            transaction
        });
        
        
        output.bank_files_payrollRun = await payroll_runs.getBank_files_payrollRun({
            transaction
        });
        
        
        
        output.journal_entries_payrollRun = await payroll_runs.getJournal_entries_payrollRun({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.approvedByUser = await payroll_runs.getApprovedByUser({
            transaction
        });
        
        
        output.postedByUser = await payroll_runs.getPostedByUser({
            transaction
        });
        
        
        output.journalEntry = await payroll_runs.getJournalEntry({
            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.users,
        as: 'approvedByUser',
        
        where: filter.approvedByUser ? {
          [Op.or]: [
            { id: { [Op.in]: filter.approvedByUser.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.approvedByUser.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

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

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.payrollType) {
                where = {
                    ...where,
                payrollType: filter.payrollType,
            };
            }
            
            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',
                        'status',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

