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

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

        const leave_applications = await db.leave_applications.create(
            {
                id: data.id || undefined,
        
        dateFrom: data.dateFrom
        ||
        null
            ,
            
        dateTo: data.dateTo
        ||
        null
            ,
            
        totalDays: data.totalDays
        ||
        null
            ,
            
        reason: data.reason
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        managerNote: data.managerNote
        ||
        null
            ,
            
        hrNote: data.hrNote
        ||
        null
            ,
            
        approvedAt: data.approvedAt
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await leave_applications.setEmployee( data.employee || null, {
            transaction,
        });
        
        await leave_applications.setLeaveType( data.leaveType || null, {
            transaction,
        });
        
        await leave_applications.setApprovedByUser( data.approvedByUser || null, {
            transaction,
        });
        

        

        

        return leave_applications;
    }
    

    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 leave_applicationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                dateFrom: item.dateFrom
            ||
            null
            ,
            
                dateTo: item.dateTo
            ||
            null
            ,
            
                totalDays: item.totalDays
            ||
            null
            ,
            
                reason: item.reason
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                managerNote: item.managerNote
            ||
            null
            ,
            
                hrNote: item.hrNote
            ||
            null
            ,
            
                approvedAt: item.approvedAt
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return leave_applications;
    }

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

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


        

        const updatePayload = {};
        
        if (data.dateFrom !== undefined) updatePayload.dateFrom = data.dateFrom;
        
        
        if (data.dateTo !== undefined) updatePayload.dateTo = data.dateTo;
        
        
        if (data.totalDays !== undefined) updatePayload.totalDays = data.totalDays;
        
        
        if (data.reason !== undefined) updatePayload.reason = data.reason;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.managerNote !== undefined) updatePayload.managerNote = data.managerNote;
        
        
        if (data.hrNote !== undefined) updatePayload.hrNote = data.hrNote;
        
        
        if (data.approvedAt !== undefined) updatePayload.approvedAt = data.approvedAt;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.employee !== undefined) {
            await leave_applications.setEmployee(
              
              data.employee,
              
              { transaction }
            );
        }
        
        if (data.leaveType !== undefined) {
            await leave_applications.setLeaveType(
              
              data.leaveType,
              
              { transaction }
            );
        }
        
        if (data.approvedByUser !== undefined) {
            await leave_applications.setApprovedByUser(
              
              data.approvedByUser,
              
              { transaction }
            );
        }
        

        
        

        

        return leave_applications;
    }

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

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

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


        return leave_applications;
    }

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

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

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

        await leave_applications.destroy({
            transaction
        });

        return leave_applications;
    }

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

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

        if (!leave_applications) {
            return leave_applications;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.employee = await leave_applications.getEmployee({
            transaction
        });
        
        
        output.leaveType = await leave_applications.getLeaveType({
            transaction
        });
        
        
        output.approvedByUser = await leave_applications.getApprovedByUser({
            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.employees,
        as: 'employee',
        
        where: filter.employee ? {
          [Op.or]: [
            { id: { [Op.in]: filter.employee.split('|').map(term => Utils.uuid(term)) } },
            {
              employeeCode: {
                [Op.or]: filter.employee.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            
            if (filter.reason) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'leave_applications',
                        'reason',
                        filter.reason,
                    ),
                };
            }
            
            if (filter.managerNote) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'leave_applications',
                        'managerNote',
                        filter.managerNote,
                    ),
                };
            }
            
            if (filter.hrNote) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'leave_applications',
                        'hrNote',
                        filter.hrNote,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

        const records = await db.leave_applications.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,
        }));
    }

    
};

