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

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

        const work_shifts = await db.work_shifts.create(
            {
                id: data.id || undefined,
        
        shift_start: data.shift_start
        ||
        null
            ,
            
        shift_end: data.shift_end
        ||
        null
            ,
            
        shift_role: data.shift_role
        ||
        null
            ,
            
        shift_status: data.shift_status
        ||
        null
            ,
            
        shift_notes: data.shift_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await work_shifts.setWork_schedule( data.work_schedule || null, {
            transaction,
        });
        
        await work_shifts.setStaff_user( data.staff_user || null, {
            transaction,
        });
        

        

        

        return work_shifts;
    }
    

    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 work_shiftsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                shift_start: item.shift_start
            ||
            null
            ,
            
                shift_end: item.shift_end
            ||
            null
            ,
            
                shift_role: item.shift_role
            ||
            null
            ,
            
                shift_status: item.shift_status
            ||
            null
            ,
            
                shift_notes: item.shift_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return work_shifts;
    }

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

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


        

        const updatePayload = {};
        
        if (data.shift_start !== undefined) updatePayload.shift_start = data.shift_start;
        
        
        if (data.shift_end !== undefined) updatePayload.shift_end = data.shift_end;
        
        
        if (data.shift_role !== undefined) updatePayload.shift_role = data.shift_role;
        
        
        if (data.shift_status !== undefined) updatePayload.shift_status = data.shift_status;
        
        
        if (data.shift_notes !== undefined) updatePayload.shift_notes = data.shift_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.work_schedule !== undefined) {
            await work_shifts.setWork_schedule(
              
              data.work_schedule,
              
              { transaction }
            );
        }
        
        if (data.staff_user !== undefined) {
            await work_shifts.setStaff_user(
              
              data.staff_user,
              
              { transaction }
            );
        }
        

        
        

        

        return work_shifts;
    }

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

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

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


        return work_shifts;
    }

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

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

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

        await work_shifts.destroy({
            transaction
        });

        return work_shifts;
    }

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

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

        if (!work_shifts) {
            return work_shifts;
        }

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

        
        
        
        
        
        
        
        
        
        output.attendance_events_work_shift = await work_shifts.getAttendance_events_work_shift({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.work_schedule = await work_shifts.getWork_schedule({
            transaction
        });
        
        
        output.staff_user = await work_shifts.getStaff_user({
            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.work_schedules,
        as: 'work_schedule',
        
        where: filter.work_schedule ? {
          [Op.or]: [
            { id: { [Op.in]: filter.work_schedule.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.work_schedule.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.shift_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'work_shifts',
                        'shift_notes',
                        filter.shift_notes,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            shift_start: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    shift_end: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

            
            if (filter.shift_role) {
                where = {
                    ...where,
                shift_role: filter.shift_role,
            };
            }
            
            if (filter.shift_status) {
                where = {
                    ...where,
                shift_status: filter.shift_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.work_shifts.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(
                        'work_shifts',
                        'shift_notes',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

