
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const { isRestrictedPayrollUser } = require('../../security/payrollAccess');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class Job_logsDBApi {
    

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

        const job_logs = await db.job_logs.create(
            {
                id: data.id || undefined,
        
        work_date: data.work_date
        ||
        null
            ,
            
        hours_conducted: data.hours_conducted
        ||
        null
            ,
            
        client_paid: data.client_paid
        ||
        null
            ,
            
        workers_comp_class: data.workers_comp_class
        ||
        null
            ,
            
        odometer_start: data.odometer_start
        ||
        null
            ,
            
        odometer_end: data.odometer_end
        ||
        null
            ,
            
        job_address: data.job_address
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        notes_to_admin: data.notes_to_admin
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await job_logs.setEmployee( data.employee || null, {
            transaction,
        });
        
        await job_logs.setCustomer( data.customer || null, {
            transaction,
        });
        
        await job_logs.setPay_type( data.pay_type || null, {
            transaction,
        });
        
        await job_logs.setVehicle( data.vehicle || null, {
            transaction,
        });
        
        await job_logs.setWorkersCompClass( data.workersCompClass || null, {
            transaction,
        });
        

        

        

        return job_logs;
    }
    

    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 job_logsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                work_date: item.work_date
            ||
            null
            ,
            
                hours_conducted: item.hours_conducted
            ||
            null
            ,
            
                client_paid: item.client_paid
            ||
            null
            ,
            
                workers_comp_class: item.workers_comp_class
            ||
            null
            ,
            
                odometer_start: item.odometer_start
            ||
            null
            ,
            
                odometer_end: item.odometer_end
            ||
            null
            ,
            
                job_address: item.job_address
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                notes_to_admin: item.notes_to_admin
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return job_logs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.work_date !== undefined) updatePayload.work_date = data.work_date;
        
        
        if (data.hours_conducted !== undefined) updatePayload.hours_conducted = data.hours_conducted;
        
        
        if (data.client_paid !== undefined) updatePayload.client_paid = data.client_paid;
        
        
        if (data.workers_comp_class !== undefined) updatePayload.workers_comp_class = data.workers_comp_class;
        
        
        if (data.odometer_start !== undefined) updatePayload.odometer_start = data.odometer_start;
        
        
        if (data.odometer_end !== undefined) updatePayload.odometer_end = data.odometer_end;
        
        
        if (data.job_address !== undefined) updatePayload.job_address = data.job_address;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.notes_to_admin !== undefined) updatePayload.notes_to_admin = data.notes_to_admin;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.employee !== undefined) {
            await job_logs.setEmployee(
              
              data.employee,
              
              { transaction }
            );
        }
        
        if (data.customer !== undefined) {
            await job_logs.setCustomer(
              
              data.customer,
              
              { transaction }
            );
        }
        
        if (data.pay_type !== undefined) {
            await job_logs.setPay_type(
              
              data.pay_type,
              
              { transaction }
            );
        }
        
        if (data.vehicle !== undefined) {
            await job_logs.setVehicle(
              
              data.vehicle,
              
              { transaction }
            );
        }
        
        if (data.workersCompClass !== undefined) {
            await job_logs.setWorkersCompClass(
              
              data.workersCompClass,
              
              { transaction }
            );
        }
        

        
        

        

        return job_logs;
    }

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

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

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


        return job_logs;
    }

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

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

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

        await job_logs.destroy({
            transaction
        });

        return job_logs;
    }

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

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

        if (job_logs && isRestrictedPayrollUser(currentUser) && job_logs.employeeId !== currentUser.id) {
            return null;
        }

        if (!job_logs) {
            return job_logs;
        }

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

        
        
        
        
        
        
        
        
        
        
        output.job_chemical_usages_job_log = await job_logs.getJob_chemical_usages_job_log({
            transaction
        });
        
        
        
        
        
        output.employee = await job_logs.getEmployee({
            transaction
        });
        
        
        output.customer = await job_logs.getCustomer({
            transaction
        });
        
        
        output.pay_type = await job_logs.getPay_type({
            transaction
        });
        
        
        output.vehicle = await job_logs.getVehicle({
            transaction
        });
        
        output.workersCompClass = await job_logs.getWorkersCompClass({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const currentUser = options?.currentUser;
        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: '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,
        
      },

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

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

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



    ];

        if (isRestrictedPayrollUser(currentUser)) {
            where = {
                ...where,
                employeeId: currentUser.id,
            };
        }

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

            
            if (filter.job_address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'job_logs',
                        'job_address',
                        filter.job_address,
                    ),
                };
            }
            
            if (filter.notes_to_admin) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'job_logs',
                        'notes_to_admin',
                        filter.notes_to_admin,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.workers_comp_class) {
                where = {
                    ...where,
                workers_comp_class: filter.workers_comp_class,
            };
            }
            
            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.job_logs.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, options) {
        const currentUser = options?.currentUser;
        let where = {};
        
        

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

        if (isRestrictedPayrollUser(currentUser)) {
            where = {
                ...where,
                employeeId: currentUser.id,
            };
        }

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

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

    
};

