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

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

        const staff_profiles = await db.staff_profiles.create(
            {
                id: data.id || undefined,
        
        job_title: data.job_title
        ||
        null
            ,
            
        employee_code: data.employee_code
        ||
        null
            ,
            
        hire_date: data.hire_date
        ||
        null
            ,
            
        can_login: data.can_login
        ||
        false
        
            ,
            
        active: data.active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await staff_profiles.setHotel( data.hotel || null, {
            transaction,
        });
        
        await staff_profiles.setUser( data.user || null, {
            transaction,
        });
        
        await staff_profiles.setDepartment( data.department || null, {
            transaction,
        });
        
        await staff_profiles.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return staff_profiles;
    }
    

    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 staff_profilesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                job_title: item.job_title
            ||
            null
            ,
            
                employee_code: item.employee_code
            ||
            null
            ,
            
                hire_date: item.hire_date
            ||
            null
            ,
            
                can_login: item.can_login
            ||
            false
        
            ,
            
                active: item.active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return staff_profiles;
    }

    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 staff_profiles = await db.staff_profiles.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.job_title !== undefined) updatePayload.job_title = data.job_title;
        
        
        if (data.employee_code !== undefined) updatePayload.employee_code = data.employee_code;
        
        
        if (data.hire_date !== undefined) updatePayload.hire_date = data.hire_date;
        
        
        if (data.can_login !== undefined) updatePayload.can_login = data.can_login;
        
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.hotel !== undefined) {
            await staff_profiles.setHotel(
              
              data.hotel,
              
              { transaction }
            );
        }
        
        if (data.user !== undefined) {
            await staff_profiles.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.department !== undefined) {
            await staff_profiles.setDepartment(
              
              data.department,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await staff_profiles.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return staff_profiles;
    }

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

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

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


        return staff_profiles;
    }

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

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

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

        await staff_profiles.destroy({
            transaction
        });

        return staff_profiles;
    }

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

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

        if (!staff_profiles) {
            return staff_profiles;
        }

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

        
        
        
        
        
        
        
        
        output.shifts_staff_profile = await staff_profiles.getShifts_staff_profile({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.housekeeping_tasks_assigned_staff_profile = await staff_profiles.getHousekeeping_tasks_assigned_staff_profile({
            transaction
        });
        
        
        output.maintenance_tickets_assigned_staff_profile = await staff_profiles.getMaintenance_tickets_assigned_staff_profile({
            transaction
        });
        
        
        
        
        
        
        
        
        output.hotel = await staff_profiles.getHotel({
            transaction
        });
        
        
        output.user = await staff_profiles.getUser({
            transaction
        });
        
        
        output.department = await staff_profiles.getDepartment({
            transaction
        });
        
        
        output.organizations = await staff_profiles.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.hotels,
        as: 'hotel',
        
        where: filter.hotel ? {
          [Op.or]: [
            { id: { [Op.in]: filter.hotel.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.hotel.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        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.departments,
        as: 'department',
        
        where: filter.department ? {
          [Op.or]: [
            { id: { [Op.in]: filter.department.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.department.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.job_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'staff_profiles',
                        'job_title',
                        filter.job_title,
                    ),
                };
            }
            
            if (filter.employee_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'staff_profiles',
                        'employee_code',
                        filter.employee_code,
                    ),
                };
            }
            

            
            

            
            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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.can_login) {
                where = {
                    ...where,
                can_login: filter.can_login,
            };
            }
            
            if (filter.active) {
                where = {
                    ...where,
                active: filter.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.staff_profiles.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(
                        'staff_profiles',
                        'employee_code',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

