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

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

        const time_records = await db.time_records.create(
            {
                id: data.id || undefined,
        
        workDate: data.workDate
        ||
        null
            ,
            
        scheduledTimeIn: data.scheduledTimeIn
        ||
        null
            ,
            
        scheduledTimeOut: data.scheduledTimeOut
        ||
        null
            ,
            
        actualTimeIn: data.actualTimeIn
        ||
        null
            ,
            
        actualTimeOut: data.actualTimeOut
        ||
        null
            ,
            
        tardinessMinutes: data.tardinessMinutes
        ||
        null
            ,
            
        undertimeMinutes: data.undertimeMinutes
        ||
        null
            ,
            
        overtimeMinutes: data.overtimeMinutes
        ||
        null
            ,
            
        nightDiffHours: data.nightDiffHours
        ||
        null
            ,
            
        workType: data.workType
        ||
        null
            ,
            
        isAbsent: data.isAbsent
        ||
        false
        
            ,
            
        isHalfDay: data.isHalfDay
        ||
        false
        
            ,
            
        halfDayType: data.halfDayType
        ||
        null
            ,
            
        source: data.source
        ||
        null
            ,
            
        modificationReason: data.modificationReason
        ||
        null
            ,
            
        approvedAt: data.approvedAt
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await time_records.setEmployee( data.employee || null, {
            transaction,
        });
        
        await time_records.setShift( data.shift || null, {
            transaction,
        });
        
        await time_records.setModifiedByUser( data.modifiedByUser || null, {
            transaction,
        });
        
        await time_records.setApprovedByUser( data.approvedByUser || null, {
            transaction,
        });
        
        await time_records.setPayrollRun( data.payrollRun || null, {
            transaction,
        });
        

        

        

        return time_records;
    }
    

    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 time_recordsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                workDate: item.workDate
            ||
            null
            ,
            
                scheduledTimeIn: item.scheduledTimeIn
            ||
            null
            ,
            
                scheduledTimeOut: item.scheduledTimeOut
            ||
            null
            ,
            
                actualTimeIn: item.actualTimeIn
            ||
            null
            ,
            
                actualTimeOut: item.actualTimeOut
            ||
            null
            ,
            
                tardinessMinutes: item.tardinessMinutes
            ||
            null
            ,
            
                undertimeMinutes: item.undertimeMinutes
            ||
            null
            ,
            
                overtimeMinutes: item.overtimeMinutes
            ||
            null
            ,
            
                nightDiffHours: item.nightDiffHours
            ||
            null
            ,
            
                workType: item.workType
            ||
            null
            ,
            
                isAbsent: item.isAbsent
            ||
            false
        
            ,
            
                isHalfDay: item.isHalfDay
            ||
            false
        
            ,
            
                halfDayType: item.halfDayType
            ||
            null
            ,
            
                source: item.source
            ||
            null
            ,
            
                modificationReason: item.modificationReason
            ||
            null
            ,
            
                approvedAt: item.approvedAt
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return time_records;
    }

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

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


        

        const updatePayload = {};
        
        if (data.workDate !== undefined) updatePayload.workDate = data.workDate;
        
        
        if (data.scheduledTimeIn !== undefined) updatePayload.scheduledTimeIn = data.scheduledTimeIn;
        
        
        if (data.scheduledTimeOut !== undefined) updatePayload.scheduledTimeOut = data.scheduledTimeOut;
        
        
        if (data.actualTimeIn !== undefined) updatePayload.actualTimeIn = data.actualTimeIn;
        
        
        if (data.actualTimeOut !== undefined) updatePayload.actualTimeOut = data.actualTimeOut;
        
        
        if (data.tardinessMinutes !== undefined) updatePayload.tardinessMinutes = data.tardinessMinutes;
        
        
        if (data.undertimeMinutes !== undefined) updatePayload.undertimeMinutes = data.undertimeMinutes;
        
        
        if (data.overtimeMinutes !== undefined) updatePayload.overtimeMinutes = data.overtimeMinutes;
        
        
        if (data.nightDiffHours !== undefined) updatePayload.nightDiffHours = data.nightDiffHours;
        
        
        if (data.workType !== undefined) updatePayload.workType = data.workType;
        
        
        if (data.isAbsent !== undefined) updatePayload.isAbsent = data.isAbsent;
        
        
        if (data.isHalfDay !== undefined) updatePayload.isHalfDay = data.isHalfDay;
        
        
        if (data.halfDayType !== undefined) updatePayload.halfDayType = data.halfDayType;
        
        
        if (data.source !== undefined) updatePayload.source = data.source;
        
        
        if (data.modificationReason !== undefined) updatePayload.modificationReason = data.modificationReason;
        
        
        if (data.approvedAt !== undefined) updatePayload.approvedAt = data.approvedAt;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.employee !== undefined) {
            await time_records.setEmployee(
              
              data.employee,
              
              { transaction }
            );
        }
        
        if (data.shift !== undefined) {
            await time_records.setShift(
              
              data.shift,
              
              { transaction }
            );
        }
        
        if (data.modifiedByUser !== undefined) {
            await time_records.setModifiedByUser(
              
              data.modifiedByUser,
              
              { transaction }
            );
        }
        
        if (data.approvedByUser !== undefined) {
            await time_records.setApprovedByUser(
              
              data.approvedByUser,
              
              { transaction }
            );
        }
        
        if (data.payrollRun !== undefined) {
            await time_records.setPayrollRun(
              
              data.payrollRun,
              
              { transaction }
            );
        }
        

        
        

        

        return time_records;
    }

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

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

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


        return time_records;
    }

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

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

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

        await time_records.destroy({
            transaction
        });

        return time_records;
    }

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

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

        if (!time_records) {
            return time_records;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.employee = await time_records.getEmployee({
            transaction
        });
        
        
        output.shift = await time_records.getShift({
            transaction
        });
        
        
        output.modifiedByUser = await time_records.getModifiedByUser({
            transaction
        });
        
        
        output.approvedByUser = await time_records.getApprovedByUser({
            transaction
        });
        
        
        output.payrollRun = await time_records.getPayrollRun({
            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.shifts,
        as: 'shift',
        
        where: filter.shift ? {
          [Op.or]: [
            { id: { [Op.in]: filter.shift.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.shift.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        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.payroll_runs,
        as: 'payrollRun',
        
        where: filter.payrollRun ? {
          [Op.or]: [
            { id: { [Op.in]: filter.payrollRun.split('|').map(term => Utils.uuid(term)) } },
            {
              status: {
                [Op.or]: filter.payrollRun.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.scheduledTimeIn) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'time_records',
                        'scheduledTimeIn',
                        filter.scheduledTimeIn,
                    ),
                };
            }
            
            if (filter.scheduledTimeOut) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'time_records',
                        'scheduledTimeOut',
                        filter.scheduledTimeOut,
                    ),
                };
            }
            
            if (filter.modificationReason) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'time_records',
                        'modificationReason',
                        filter.modificationReason,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    nightDiffHours: {
                    ...where.nightDiffHours,
                            [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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.workType) {
                where = {
                    ...where,
                workType: filter.workType,
            };
            }
            
            if (filter.isAbsent) {
                where = {
                    ...where,
                isAbsent: filter.isAbsent,
            };
            }
            
            if (filter.isHalfDay) {
                where = {
                    ...where,
                isHalfDay: filter.isHalfDay,
            };
            }
            
            if (filter.halfDayType) {
                where = {
                    ...where,
                halfDayType: filter.halfDayType,
            };
            }
            
            if (filter.source) {
                where = {
                    ...where,
                source: filter.source,
            };
            }
            


      

      

      

      

      



            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.time_records.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(
                        'time_records',
                        'scheduledTimeIn',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

