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

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

        const employee_hr_records = await db.employee_hr_records.create(
            {
                id: data.id || undefined,
        
        contract_number: data.contract_number
        ||
        null
            ,
            
        hire_date: data.hire_date
        ||
        null
            ,
            
        contract_type: data.contract_type
        ||
        null
            ,
            
        position: data.position
        ||
        null
            ,
            
        work_schedule: data.work_schedule
        ||
        null
            ,
            
        probation_days: data.probation_days
        ||
        null
            ,
            
        salary: data.salary
        ||
        null
            ,
            
        daily_allowance: data.daily_allowance
        ||
        null
            ,
            
        bonuses: data.bonuses
        ||
        null
            ,
            
        deductions: data.deductions
        ||
        null
            ,
            
        bank_account_iban: data.bank_account_iban
        ||
        null
            ,
            
        bank_name: data.bank_name
        ||
        null
            ,
            
        insurance_number: data.insurance_number
        ||
        null
            ,
            
        tax_number: data.tax_number
        ||
        null
            ,
            
        tax_category: data.tax_category
        ||
        null
            ,
            
        vacation_days: data.vacation_days
        ||
        null
            ,
            
        used_vacation_days: data.used_vacation_days
        ||
        null
            ,
            
        employment_status: data.employment_status
        ||
        null
            ,
            
        termination_date: data.termination_date
        ||
        null
            ,
            
        termination_reason: data.termination_reason
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await employee_hr_records.setEmployee( data.employee || null, {
            transaction,
        });
        

        

        

        return employee_hr_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 employee_hr_recordsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                contract_number: item.contract_number
            ||
            null
            ,
            
                hire_date: item.hire_date
            ||
            null
            ,
            
                contract_type: item.contract_type
            ||
            null
            ,
            
                position: item.position
            ||
            null
            ,
            
                work_schedule: item.work_schedule
            ||
            null
            ,
            
                probation_days: item.probation_days
            ||
            null
            ,
            
                salary: item.salary
            ||
            null
            ,
            
                daily_allowance: item.daily_allowance
            ||
            null
            ,
            
                bonuses: item.bonuses
            ||
            null
            ,
            
                deductions: item.deductions
            ||
            null
            ,
            
                bank_account_iban: item.bank_account_iban
            ||
            null
            ,
            
                bank_name: item.bank_name
            ||
            null
            ,
            
                insurance_number: item.insurance_number
            ||
            null
            ,
            
                tax_number: item.tax_number
            ||
            null
            ,
            
                tax_category: item.tax_category
            ||
            null
            ,
            
                vacation_days: item.vacation_days
            ||
            null
            ,
            
                used_vacation_days: item.used_vacation_days
            ||
            null
            ,
            
                employment_status: item.employment_status
            ||
            null
            ,
            
                termination_date: item.termination_date
            ||
            null
            ,
            
                termination_reason: item.termination_reason
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return employee_hr_records;
    }

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

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


        

        const updatePayload = {};
        
        if (data.contract_number !== undefined) updatePayload.contract_number = data.contract_number;
        
        
        if (data.hire_date !== undefined) updatePayload.hire_date = data.hire_date;
        
        
        if (data.contract_type !== undefined) updatePayload.contract_type = data.contract_type;
        
        
        if (data.position !== undefined) updatePayload.position = data.position;
        
        
        if (data.work_schedule !== undefined) updatePayload.work_schedule = data.work_schedule;
        
        
        if (data.probation_days !== undefined) updatePayload.probation_days = data.probation_days;
        
        
        if (data.salary !== undefined) updatePayload.salary = data.salary;
        
        
        if (data.daily_allowance !== undefined) updatePayload.daily_allowance = data.daily_allowance;
        
        
        if (data.bonuses !== undefined) updatePayload.bonuses = data.bonuses;
        
        
        if (data.deductions !== undefined) updatePayload.deductions = data.deductions;
        
        
        if (data.bank_account_iban !== undefined) updatePayload.bank_account_iban = data.bank_account_iban;
        
        
        if (data.bank_name !== undefined) updatePayload.bank_name = data.bank_name;
        
        
        if (data.insurance_number !== undefined) updatePayload.insurance_number = data.insurance_number;
        
        
        if (data.tax_number !== undefined) updatePayload.tax_number = data.tax_number;
        
        
        if (data.tax_category !== undefined) updatePayload.tax_category = data.tax_category;
        
        
        if (data.vacation_days !== undefined) updatePayload.vacation_days = data.vacation_days;
        
        
        if (data.used_vacation_days !== undefined) updatePayload.used_vacation_days = data.used_vacation_days;
        
        
        if (data.employment_status !== undefined) updatePayload.employment_status = data.employment_status;
        
        
        if (data.termination_date !== undefined) updatePayload.termination_date = data.termination_date;
        
        
        if (data.termination_reason !== undefined) updatePayload.termination_reason = data.termination_reason;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return employee_hr_records;
    }

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

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

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


        return employee_hr_records;
    }

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

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

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

        await employee_hr_records.destroy({
            transaction
        });

        return employee_hr_records;
    }

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

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

        if (!employee_hr_records) {
            return employee_hr_records;
        }

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

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



    ];

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

            
            if (filter.contract_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employee_hr_records',
                        'contract_number',
                        filter.contract_number,
                    ),
                };
            }
            
            if (filter.position) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employee_hr_records',
                        'position',
                        filter.position,
                    ),
                };
            }
            
            if (filter.work_schedule) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employee_hr_records',
                        'work_schedule',
                        filter.work_schedule,
                    ),
                };
            }
            
            if (filter.bank_account_iban) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employee_hr_records',
                        'bank_account_iban',
                        filter.bank_account_iban,
                    ),
                };
            }
            
            if (filter.bank_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employee_hr_records',
                        'bank_name',
                        filter.bank_name,
                    ),
                };
            }
            
            if (filter.insurance_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employee_hr_records',
                        'insurance_number',
                        filter.insurance_number,
                    ),
                };
            }
            
            if (filter.tax_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employee_hr_records',
                        'tax_number',
                        filter.tax_number,
                    ),
                };
            }
            
            if (filter.tax_category) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employee_hr_records',
                        'tax_category',
                        filter.tax_category,
                    ),
                };
            }
            
            if (filter.termination_reason) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employee_hr_records',
                        'termination_reason',
                        filter.termination_reason,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.contract_type) {
                where = {
                    ...where,
                contract_type: filter.contract_type,
            };
            }
            
            if (filter.employment_status) {
                where = {
                    ...where,
                employment_status: filter.employment_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.employee_hr_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(
                        'employee_hr_records',
                        'contract_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

