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

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

        const time_entries = await db.time_entries.create(
            {
                id: data.id || undefined,
        
        clock_in_at: data.clock_in_at
        ||
        null
            ,
            
        clock_out_at: data.clock_out_at
        ||
        null
            ,
            
        clock_in_source: data.clock_in_source
        ||
        null
            ,
            
        clock_out_source: data.clock_out_source
        ||
        null
            ,
            
        worked_hours: data.worked_hours
        ||
        null
            ,
            
        break_hours: data.break_hours
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        note: data.note
        ||
        null
            ,
            
        approved_at: data.approved_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await time_entries.setEmployee( data.employee || null, {
            transaction,
        });
        
        await time_entries.setApproved_by( data.approved_by || null, {
            transaction,
        });
        
        await time_entries.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return time_entries;
    }
    

    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 time_entriesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                clock_in_at: item.clock_in_at
            ||
            null
            ,
            
                clock_out_at: item.clock_out_at
            ||
            null
            ,
            
                clock_in_source: item.clock_in_source
            ||
            null
            ,
            
                clock_out_source: item.clock_out_source
            ||
            null
            ,
            
                worked_hours: item.worked_hours
            ||
            null
            ,
            
                break_hours: item.break_hours
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                note: item.note
            ||
            null
            ,
            
                approved_at: item.approved_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return time_entries;
    }

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


        

        const updatePayload = {};
        
        if (data.clock_in_at !== undefined) updatePayload.clock_in_at = data.clock_in_at;
        
        
        if (data.clock_out_at !== undefined) updatePayload.clock_out_at = data.clock_out_at;
        
        
        if (data.clock_in_source !== undefined) updatePayload.clock_in_source = data.clock_in_source;
        
        
        if (data.clock_out_source !== undefined) updatePayload.clock_out_source = data.clock_out_source;
        
        
        if (data.worked_hours !== undefined) updatePayload.worked_hours = data.worked_hours;
        
        
        if (data.break_hours !== undefined) updatePayload.break_hours = data.break_hours;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.note !== undefined) updatePayload.note = data.note;
        
        
        if (data.approved_at !== undefined) updatePayload.approved_at = data.approved_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.employee !== undefined) {
            await time_entries.setEmployee(
              
              data.employee,
              
              { transaction }
            );
        }
        
        if (data.approved_by !== undefined) {
            await time_entries.setApproved_by(
              
              data.approved_by,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await time_entries.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return time_entries;
    }

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

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

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


        return time_entries;
    }

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

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

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

        await time_entries.destroy({
            transaction
        });

        return time_entries;
    }

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

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

        if (!time_entries) {
            return time_entries;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.employee = await time_entries.getEmployee({
            transaction
        });
        
        
        output.approved_by = await time_entries.getApproved_by({
            transaction
        });
        
        
        output.organizations = await time_entries.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.employees,
        as: 'employee',
        
        where: filter.employee ? {
          [Op.or]: [
            { id: { [Op.in]: filter.employee.split('|').map(term => Utils.uuid(term)) } },
            {
              employee_number: {
                [Op.or]: filter.employee.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.employees,
        as: 'approved_by',
        
        where: filter.approved_by ? {
          [Op.or]: [
            { id: { [Op.in]: filter.approved_by.split('|').map(term => Utils.uuid(term)) } },
            {
              employee_number: {
                [Op.or]: filter.approved_by.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.clock_in_source) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'time_entries',
                        'clock_in_source',
                        filter.clock_in_source,
                    ),
                };
            }
            
            if (filter.clock_out_source) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'time_entries',
                        'clock_out_source',
                        filter.clock_out_source,
                    ),
                };
            }
            
            if (filter.note) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'time_entries',
                        'note',
                        filter.note,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    approved_at: {
                    ...where.approved_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.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.time_entries.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(
                        'time_entries',
                        'status',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

