
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,
        
        job_title: data.job_title
        ||
        null
            ,
            
        employment_status: data.employment_status
        ||
        null
            ,
            
        daily_wage: data.daily_wage
        ||
        null
            ,
            
        hired_at: data.hired_at
        ||
        null
            ,
            
        can_operate_register: data.can_operate_register
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await employees.setStore( data.store || null, {
            transaction,
        });
        
        await employees.setNpc( data.npc || 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,
                
                job_title: item.job_title
            ||
            null
            ,
            
                employment_status: item.employment_status
            ||
            null
            ,
            
                daily_wage: item.daily_wage
            ||
            null
            ,
            
                hired_at: item.hired_at
            ||
            null
            ,
            
                can_operate_register: item.can_operate_register
            ||
            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 employees = await db.employees.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.job_title !== undefined) updatePayload.job_title = data.job_title;
        
        
        if (data.employment_status !== undefined) updatePayload.employment_status = data.employment_status;
        
        
        if (data.daily_wage !== undefined) updatePayload.daily_wage = data.daily_wage;
        
        
        if (data.hired_at !== undefined) updatePayload.hired_at = data.hired_at;
        
        
        if (data.can_operate_register !== undefined) updatePayload.can_operate_register = data.can_operate_register;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.store !== undefined) {
            await employees.setStore(
              
              data.store,
              
              { transaction }
            );
        }
        
        if (data.npc !== undefined) {
            await employees.setNpc(
              
              data.npc,
              
              { 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.deliveries_received_by_employee = await employees.getDeliveries_received_by_employee({
            transaction
        });
        
        
        
        
        
        output.sales_transactions_cashier_employee = await employees.getSales_transactions_cashier_employee({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.store = await employees.getStore({
            transaction
        });
        
        
        output.npc = await employees.getNpc({
            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.market_stores,
        as: 'store',
        
        where: filter.store ? {
          [Op.or]: [
            { id: { [Op.in]: filter.store.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.store.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            

            
            

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

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

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

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

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

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

            
            if (filter.job_title) {
                where = {
                    ...where,
                job_title: filter.job_title,
            };
            }
            
            if (filter.employment_status) {
                where = {
                    ...where,
                employment_status: filter.employment_status,
            };
            }
            
            if (filter.can_operate_register) {
                where = {
                    ...where,
                can_operate_register: filter.can_operate_register,
            };
            }
            


      

      



            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.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, ) {
        let where = {};
        
        

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

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

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

    
};

