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

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

        const attendance_events = await db.attendance_events.create(
            {
                id: data.id || undefined,
        
        event_type: data.event_type
        ||
        null
            ,
            
        event_time: data.event_time
        ||
        null
            ,
            
        latitude: data.latitude
        ||
        null
            ,
            
        longitude: data.longitude
        ||
        null
            ,
            
        distance_meters: data.distance_meters
        ||
        null
            ,
            
        out_of_geofence: data.out_of_geofence
        ||
        false
        
            ,
            
        comment: data.comment
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await attendance_events.setRestaurant( data.restaurant || null, {
            transaction,
        });
        
        await attendance_events.setStaff_user( data.staff_user || null, {
            transaction,
        });
        
        await attendance_events.setWork_shift( data.work_shift || null, {
            transaction,
        });
        

        

        

        return attendance_events;
    }
    

    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 attendance_eventsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                event_type: item.event_type
            ||
            null
            ,
            
                event_time: item.event_time
            ||
            null
            ,
            
                latitude: item.latitude
            ||
            null
            ,
            
                longitude: item.longitude
            ||
            null
            ,
            
                distance_meters: item.distance_meters
            ||
            null
            ,
            
                out_of_geofence: item.out_of_geofence
            ||
            false
        
            ,
            
                comment: item.comment
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return attendance_events;
    }

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

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


        

        const updatePayload = {};
        
        if (data.event_type !== undefined) updatePayload.event_type = data.event_type;
        
        
        if (data.event_time !== undefined) updatePayload.event_time = data.event_time;
        
        
        if (data.latitude !== undefined) updatePayload.latitude = data.latitude;
        
        
        if (data.longitude !== undefined) updatePayload.longitude = data.longitude;
        
        
        if (data.distance_meters !== undefined) updatePayload.distance_meters = data.distance_meters;
        
        
        if (data.out_of_geofence !== undefined) updatePayload.out_of_geofence = data.out_of_geofence;
        
        
        if (data.comment !== undefined) updatePayload.comment = data.comment;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.restaurant !== undefined) {
            await attendance_events.setRestaurant(
              
              data.restaurant,
              
              { transaction }
            );
        }
        
        if (data.staff_user !== undefined) {
            await attendance_events.setStaff_user(
              
              data.staff_user,
              
              { transaction }
            );
        }
        
        if (data.work_shift !== undefined) {
            await attendance_events.setWork_shift(
              
              data.work_shift,
              
              { transaction }
            );
        }
        

        
        

        

        return attendance_events;
    }

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

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

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


        return attendance_events;
    }

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

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

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

        await attendance_events.destroy({
            transaction
        });

        return attendance_events;
    }

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

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

        if (!attendance_events) {
            return attendance_events;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.restaurant = await attendance_events.getRestaurant({
            transaction
        });
        
        
        output.staff_user = await attendance_events.getStaff_user({
            transaction
        });
        
        
        output.work_shift = await attendance_events.getWork_shift({
            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.restaurants,
        as: 'restaurant',
        
        where: filter.restaurant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.restaurant.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.restaurant.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}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

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

            
            

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

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

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

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

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

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

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

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

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

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

            
            if (filter.event_type) {
                where = {
                    ...where,
                event_type: filter.event_type,
            };
            }
            
            if (filter.out_of_geofence) {
                where = {
                    ...where,
                out_of_geofence: filter.out_of_geofence,
            };
            }
            


      

      

      



            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.attendance_events.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(
                        'attendance_events',
                        'event_type',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

