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

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

        const employees = await db.employees.create(
            {
                id: data.id || undefined,
        
        employee_code: data.employee_code
        ||
        null
            ,
            
        full_name: data.full_name
        ||
        null
            ,
            
        phone: data.phone
        ||
        null
            ,
            
        nik: data.nik
        ||
        null
            ,
            
        npwp: data.npwp
        ||
        null
            ,
            
        bank_name: data.bank_name
        ||
        null
            ,
            
        bank_account_number: data.bank_account_number
        ||
        null
            ,
            
        bank_account_name: data.bank_account_name
        ||
        null
            ,
            
        employment_status: data.employment_status
        ||
        null
            ,
            
        join_date: data.join_date
        ||
        null
            ,
            
        resign_date: data.resign_date
        ||
        null
            ,
            
        base_salary_monthly: data.base_salary_monthly
        ||
        null
            ,
            
        position_allowance_fixed: data.position_allowance_fixed
        ||
        null
            ,
            
        meal_allowance_daily: data.meal_allowance_daily
        ||
        null
            ,
            
        transport_allowance_daily: data.transport_allowance_daily
        ||
        null
            ,
            
        prorate_position_allowance_under_20_days: data.prorate_position_allowance_under_20_days
        ||
        false
        
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await employees.setUser( data.user || null, {
            transaction,
        });
        
        await employees.setOutlet( data.outlet || null, {
            transaction,
        });
        
        await employees.setJob_position( data.job_position || null, {
            transaction,
        });
        
        await employees.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return employees;
    }
    

    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 employeesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                employee_code: item.employee_code
            ||
            null
            ,
            
                full_name: item.full_name
            ||
            null
            ,
            
                phone: item.phone
            ||
            null
            ,
            
                nik: item.nik
            ||
            null
            ,
            
                npwp: item.npwp
            ||
            null
            ,
            
                bank_name: item.bank_name
            ||
            null
            ,
            
                bank_account_number: item.bank_account_number
            ||
            null
            ,
            
                bank_account_name: item.bank_account_name
            ||
            null
            ,
            
                employment_status: item.employment_status
            ||
            null
            ,
            
                join_date: item.join_date
            ||
            null
            ,
            
                resign_date: item.resign_date
            ||
            null
            ,
            
                base_salary_monthly: item.base_salary_monthly
            ||
            null
            ,
            
                position_allowance_fixed: item.position_allowance_fixed
            ||
            null
            ,
            
                meal_allowance_daily: item.meal_allowance_daily
            ||
            null
            ,
            
                transport_allowance_daily: item.transport_allowance_daily
            ||
            null
            ,
            
                prorate_position_allowance_under_20_days: item.prorate_position_allowance_under_20_days
            ||
            false
        
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return employees;
    }

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

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


        

        const updatePayload = {};
        
        if (data.employee_code !== undefined) updatePayload.employee_code = data.employee_code;
        
        
        if (data.full_name !== undefined) updatePayload.full_name = data.full_name;
        
        
        if (data.phone !== undefined) updatePayload.phone = data.phone;
        
        
        if (data.nik !== undefined) updatePayload.nik = data.nik;
        
        
        if (data.npwp !== undefined) updatePayload.npwp = data.npwp;
        
        
        if (data.bank_name !== undefined) updatePayload.bank_name = data.bank_name;
        
        
        if (data.bank_account_number !== undefined) updatePayload.bank_account_number = data.bank_account_number;
        
        
        if (data.bank_account_name !== undefined) updatePayload.bank_account_name = data.bank_account_name;
        
        
        if (data.employment_status !== undefined) updatePayload.employment_status = data.employment_status;
        
        
        if (data.join_date !== undefined) updatePayload.join_date = data.join_date;
        
        
        if (data.resign_date !== undefined) updatePayload.resign_date = data.resign_date;
        
        
        if (data.base_salary_monthly !== undefined) updatePayload.base_salary_monthly = data.base_salary_monthly;
        
        
        if (data.position_allowance_fixed !== undefined) updatePayload.position_allowance_fixed = data.position_allowance_fixed;
        
        
        if (data.meal_allowance_daily !== undefined) updatePayload.meal_allowance_daily = data.meal_allowance_daily;
        
        
        if (data.transport_allowance_daily !== undefined) updatePayload.transport_allowance_daily = data.transport_allowance_daily;
        
        
        if (data.prorate_position_allowance_under_20_days !== undefined) updatePayload.prorate_position_allowance_under_20_days = data.prorate_position_allowance_under_20_days;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await employees.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.outlet !== undefined) {
            await employees.setOutlet(
              
              data.outlet,
              
              { transaction }
            );
        }
        
        if (data.job_position !== undefined) {
            await employees.setJob_position(
              
              data.job_position,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await employees.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return employees;
    }

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

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

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


        return employees;
    }

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

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

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

        await employees.destroy({
            transaction
        });

        return employees;
    }

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

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

        if (!employees) {
            return employees;
        }

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

        
        
        
        
        
        
        
        
        output.employee_contracts_employee = await employees.getEmployee_contracts_employee({
            transaction
        });
        
        
        output.attendance_logs_employee = await employees.getAttendance_logs_employee({
            transaction
        });
        
        
        output.attendance_requests_employee = await employees.getAttendance_requests_employee({
            transaction
        });
        
        
        output.overtime_logs_employee = await employees.getOvertime_logs_employee({
            transaction
        });
        
        
        output.disciplinary_actions_employee = await employees.getDisciplinary_actions_employee({
            transaction
        });
        
        
        
        output.kpi_scores_employee = await employees.getKpi_scores_employee({
            transaction
        });
        
        
        
        
        output.loan_accounts_employee = await employees.getLoan_accounts_employee({
            transaction
        });
        
        
        
        output.payroll_items_employee = await employees.getPayroll_items_employee({
            transaction
        });
        
        
        
        
        
        
        
        output.user = await employees.getUser({
            transaction
        });
        
        
        output.outlet = await employees.getOutlet({
            transaction
        });
        
        
        output.job_position = await employees.getJob_position({
            transaction
        });
        
        
        output.organizations = await employees.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

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

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.employee_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'employee_code',
                        filter.employee_code,
                    ),
                };
            }
            
            if (filter.full_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'full_name',
                        filter.full_name,
                    ),
                };
            }
            
            if (filter.phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'phone',
                        filter.phone,
                    ),
                };
            }
            
            if (filter.nik) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'nik',
                        filter.nik,
                    ),
                };
            }
            
            if (filter.npwp) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'npwp',
                        filter.npwp,
                    ),
                };
            }
            
            if (filter.bank_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'bank_name',
                        filter.bank_name,
                    ),
                };
            }
            
            if (filter.bank_account_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'bank_account_number',
                        filter.bank_account_number,
                    ),
                };
            }
            
            if (filter.bank_account_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'bank_account_name',
                        filter.bank_account_name,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.employment_status) {
                where = {
                    ...where,
                employment_status: filter.employment_status,
            };
            }
            
            if (filter.prorate_position_allowance_under_20_days) {
                where = {
                    ...where,
                prorate_position_allowance_under_20_days: filter.prorate_position_allowance_under_20_days,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            


      

      

      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.employees.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

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

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

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

    
};

