
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,
        
        first_name: data.first_name
        ||
        null
            ,
            
        middle_name: data.middle_name
        ||
        null
            ,
            
        last_name: data.last_name
        ||
        null
            ,
            
        national_id: data.national_id
        ||
        null
            ,
            
        birth_date: data.birth_date
        ||
        null
            ,
            
        nationality: data.nationality
        ||
        null
            ,
            
        email: data.email
        ||
        null
            ,
            
        phone: data.phone
        ||
        null
            ,
            
        phone2: data.phone2
        ||
        null
            ,
            
        permanent_address: data.permanent_address
        ||
        null
            ,
            
        current_address: data.current_address
        ||
        null
            ,
            
        emergency_contact: data.emergency_contact
        ||
        null
            ,
            
        emergency_phone: data.emergency_phone
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
        is_driver: data.is_driver
        ||
        false
        
            ,
            
        is_dispatcher: data.is_dispatcher
        ||
        false
        
            ,
            
        is_accounting: data.is_accounting
        ||
        false
        
            ,
            
        deleted_at: data.deleted_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await employees.setCompany( data.company || 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,
                
                first_name: item.first_name
            ||
            null
            ,
            
                middle_name: item.middle_name
            ||
            null
            ,
            
                last_name: item.last_name
            ||
            null
            ,
            
                national_id: item.national_id
            ||
            null
            ,
            
                birth_date: item.birth_date
            ||
            null
            ,
            
                nationality: item.nationality
            ||
            null
            ,
            
                email: item.email
            ||
            null
            ,
            
                phone: item.phone
            ||
            null
            ,
            
                phone2: item.phone2
            ||
            null
            ,
            
                permanent_address: item.permanent_address
            ||
            null
            ,
            
                current_address: item.current_address
            ||
            null
            ,
            
                emergency_contact: item.emergency_contact
            ||
            null
            ,
            
                emergency_phone: item.emergency_phone
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
                is_driver: item.is_driver
            ||
            false
        
            ,
            
                is_dispatcher: item.is_dispatcher
            ||
            false
        
            ,
            
                is_accounting: item.is_accounting
            ||
            false
        
            ,
            
                deleted_at: item.deleted_at
            ||
            null
            ,
            
            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.first_name !== undefined) updatePayload.first_name = data.first_name;
        
        
        if (data.middle_name !== undefined) updatePayload.middle_name = data.middle_name;
        
        
        if (data.last_name !== undefined) updatePayload.last_name = data.last_name;
        
        
        if (data.national_id !== undefined) updatePayload.national_id = data.national_id;
        
        
        if (data.birth_date !== undefined) updatePayload.birth_date = data.birth_date;
        
        
        if (data.nationality !== undefined) updatePayload.nationality = data.nationality;
        
        
        if (data.email !== undefined) updatePayload.email = data.email;
        
        
        if (data.phone !== undefined) updatePayload.phone = data.phone;
        
        
        if (data.phone2 !== undefined) updatePayload.phone2 = data.phone2;
        
        
        if (data.permanent_address !== undefined) updatePayload.permanent_address = data.permanent_address;
        
        
        if (data.current_address !== undefined) updatePayload.current_address = data.current_address;
        
        
        if (data.emergency_contact !== undefined) updatePayload.emergency_contact = data.emergency_contact;
        
        
        if (data.emergency_phone !== undefined) updatePayload.emergency_phone = data.emergency_phone;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        if (data.is_driver !== undefined) updatePayload.is_driver = data.is_driver;
        
        
        if (data.is_dispatcher !== undefined) updatePayload.is_dispatcher = data.is_dispatcher;
        
        
        if (data.is_accounting !== undefined) updatePayload.is_accounting = data.is_accounting;
        
        
        if (data.deleted_at !== undefined) updatePayload.deleted_at = data.deleted_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await employees.setCompany(
              
              data.company,
              
              { 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_assignments_employee = await employees.getEmployee_assignments_employee({
            transaction
        });
        
        
        output.employee_hr_records_employee = await employees.getEmployee_hr_records_employee({
            transaction
        });
        
        
        output.driver_profiles_employee = await employees.getDriver_profiles_employee({
            transaction
        });
        
        
        
        output.incidents_employee = await employees.getIncidents_employee({
            transaction
        });
        
        
        output.documents_employee = await employees.getDocuments_employee({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.driver_vehicle_assignments_employee = await employees.getDriver_vehicle_assignments_employee({
            transaction
        });
        
        
        
        
        
        output.trips_driver = await employees.getTrips_driver({
            transaction
        });
        
        
        
        
        
        
        
        output.cost_items_employee = await employees.getCost_items_employee({
            transaction
        });
        
        
        
        
        
        
        output.company = await employees.getCompany({
            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.companies,
        as: 'company',
        
        where: filter.company ? {
          [Op.or]: [
            { id: { [Op.in]: filter.company.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.first_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'first_name',
                        filter.first_name,
                    ),
                };
            }
            
            if (filter.middle_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'middle_name',
                        filter.middle_name,
                    ),
                };
            }
            
            if (filter.last_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'last_name',
                        filter.last_name,
                    ),
                };
            }
            
            if (filter.national_id) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'national_id',
                        filter.national_id,
                    ),
                };
            }
            
            if (filter.nationality) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'nationality',
                        filter.nationality,
                    ),
                };
            }
            
            if (filter.email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'email',
                        filter.email,
                    ),
                };
            }
            
            if (filter.phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'phone',
                        filter.phone,
                    ),
                };
            }
            
            if (filter.phone2) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'phone2',
                        filter.phone2,
                    ),
                };
            }
            
            if (filter.permanent_address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'permanent_address',
                        filter.permanent_address,
                    ),
                };
            }
            
            if (filter.current_address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'current_address',
                        filter.current_address,
                    ),
                };
            }
            
            if (filter.emergency_contact) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'emergency_contact',
                        filter.emergency_contact,
                    ),
                };
            }
            
            if (filter.emergency_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'emergency_phone',
                        filter.emergency_phone,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.is_driver) {
                where = {
                    ...where,
                is_driver: filter.is_driver,
            };
            }
            
            if (filter.is_dispatcher) {
                where = {
                    ...where,
                is_dispatcher: filter.is_dispatcher,
            };
            }
            
            if (filter.is_accounting) {
                where = {
                    ...where,
                is_accounting: filter.is_accounting,
            };
            }
            


      



            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',
                        'last_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

