
const db = require('../models');
const FileDBApi = require('./file');
const Utils = require('../utils');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class Attendance_logsDBApi {
    

    
    static async create(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;
            const attendance_logs = await db.attendance_logs.create(
            {
                id: data.id || undefined,
        
        work_date: data.work_date
        ||
        null
            ,
            
        check_in_at: data.check_in_at
        ||
        null
            ,
            
        check_out_at: data.check_out_at
        ||
        null
            ,
            
        check_in_lat: data.check_in_lat
        ??
        null
            ,
            
        check_in_lng: data.check_in_lng
        ??
        null
            ,
            
        check_out_lat: data.check_out_lat
        ??
        null
            ,
            
        check_out_lng: data.check_out_lng
        ??
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        late_minutes: data.late_minutes
        ??
        null
            ,
            
        gps_valid: data.gps_valid
        ||
        false
        
            ,
            
        remarks: data.remarks
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await attendance_logs.setEmployee( data.employee || null, {
            transaction,
        });
        
        await attendance_logs.setOutlet( data.outlet || null, {
            transaction,
        });
        
        await attendance_logs.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.attendance_logs.getTableName(),
                belongsToColumn: 'check_in_photo',
                belongsToId: attendance_logs.id,
            },
            data.check_in_photo,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.attendance_logs.getTableName(),
                belongsToColumn: 'check_out_photo',
                belongsToId: attendance_logs.id,
            },
            data.check_out_photo,
            options,
        );
        

        return attendance_logs;
    }
    

    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_logsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                work_date: item.work_date
            ||
            null
            ,
            
                check_in_at: item.check_in_at
            ||
            null
            ,
            
                check_out_at: item.check_out_at
            ||
            null
            ,
            
                check_in_lat: item.check_in_lat
            ??
            null
            ,
            
                check_in_lng: item.check_in_lng
            ??
            null
            ,
            
                check_out_lat: item.check_out_lat
            ??
            null
            ,
            
                check_out_lng: item.check_out_lng
            ??
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                late_minutes: item.late_minutes
            ??
            null
            ,
            
                gps_valid: item.gps_valid
            ||
            false
        
            ,
            
                remarks: item.remarks
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < attendance_logs.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.attendance_logs.getTableName(),
                    belongsToColumn: 'check_in_photo',
                    belongsToId: attendance_logs[i].id,
                },
                data[i].check_in_photo,
                options,
            );
        }
        
        for (let i = 0; i < attendance_logs.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.attendance_logs.getTableName(),
                    belongsToColumn: 'check_out_photo',
                    belongsToId: attendance_logs[i].id,
                },
                data[i].check_out_photo,
                options,
            );
        }
        

        return attendance_logs;
    }

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


        

        const updatePayload = {};
        
        if (data.work_date !== undefined) updatePayload.work_date = data.work_date;
        
        
        if (data.check_in_at !== undefined) updatePayload.check_in_at = data.check_in_at;
        
        
        if (data.check_out_at !== undefined) updatePayload.check_out_at = data.check_out_at;
        
        
        if (data.check_in_lat !== undefined) updatePayload.check_in_lat = data.check_in_lat;
        
        
        if (data.check_in_lng !== undefined) updatePayload.check_in_lng = data.check_in_lng;
        
        
        if (data.check_out_lat !== undefined) updatePayload.check_out_lat = data.check_out_lat;
        
        
        if (data.check_out_lng !== undefined) updatePayload.check_out_lng = data.check_out_lng;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.late_minutes !== undefined) updatePayload.late_minutes = data.late_minutes;
        
        
        if (data.gps_valid !== undefined) updatePayload.gps_valid = data.gps_valid;
        
        
        if (data.remarks !== undefined) updatePayload.remarks = data.remarks;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.employee !== undefined) {
            await attendance_logs.setEmployee(
              
              data.employee,
              
              { transaction }
            );
        }
        
        if (data.outlet !== undefined) {
            await attendance_logs.setOutlet(
              
              data.outlet,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await attendance_logs.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.attendance_logs.getTableName(),
                belongsToColumn: 'check_in_photo',
                belongsToId: attendance_logs.id,
            },
            data.check_in_photo,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.attendance_logs.getTableName(),
                belongsToColumn: 'check_out_photo',
                belongsToId: attendance_logs.id,
            },
            data.check_out_photo,
            options,
        );
        

        return attendance_logs;
    }

    static async deleteByIds(ids, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;
            const attendance_logs = await db.attendance_logs.findAll({
            where: {
                id: {
                    [Op.in]: ids,
                },
            },
            transaction,
        });

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


        return attendance_logs;
    }

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

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

        await attendance_logs.destroy({
            transaction
        });

        return attendance_logs;
    }

    static async findBy(where, options) {
        const transaction = (options && options.transaction) || undefined;
            const attendance_logs = await db.attendance_logs.findOne(
            { where },
            { transaction },
        );

        if (!attendance_logs) {
            return attendance_logs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.employee = await attendance_logs.getEmployee({
            transaction
        });
        
        
        output.outlet = await attendance_logs.getOutlet({
            transaction
        });
        
        
        output.check_in_photo = await attendance_logs.getCheck_in_photo({
            transaction
        });
        
        
        output.check_out_photo = await attendance_logs.getCheck_out_photo({
            transaction
        });
        
        
        output.organizations = await attendance_logs.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;

    let include = [

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

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



      {
        model: db.file,
        as: 'check_in_photo',
      },

      {
        model: db.file,
        as: 'check_out_photo',
      },

    ];

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    late_minutes: {
                    ...where.late_minutes,
                            [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.gps_valid) {
                where = {
                    ...where,
                gps_valid: filter.gps_valid,
            };
            }
            


      

      

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

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

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

    
};

