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

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

        const expense_claims = await db.expense_claims.create(
            {
                id: data.id || undefined,
        
        expense_date: data.expense_date
        ||
        null
            ,
            
        amount: data.amount
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        merchant: data.merchant
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        decision_at: data.decision_at
        ||
        null
            ,
            
        decision_comment: data.decision_comment
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await expense_claims.setEmployee( data.employee || null, {
            transaction,
        });
        
        await expense_claims.setExpense_category( data.expense_category || null, {
            transaction,
        });
        
        await expense_claims.setApprover( data.approver || null, {
            transaction,
        });
        
        await expense_claims.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return expense_claims;
    }
    

    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 expense_claimsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                expense_date: item.expense_date
            ||
            null
            ,
            
                amount: item.amount
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                merchant: item.merchant
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                submitted_at: item.submitted_at
            ||
            null
            ,
            
                decision_at: item.decision_at
            ||
            null
            ,
            
                decision_comment: item.decision_comment
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return expense_claims;
    }

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


        

        const updatePayload = {};
        
        if (data.expense_date !== undefined) updatePayload.expense_date = data.expense_date;
        
        
        if (data.amount !== undefined) updatePayload.amount = data.amount;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.merchant !== undefined) updatePayload.merchant = data.merchant;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.decision_at !== undefined) updatePayload.decision_at = data.decision_at;
        
        
        if (data.decision_comment !== undefined) updatePayload.decision_comment = data.decision_comment;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.employee !== undefined) {
            await expense_claims.setEmployee(
              
              data.employee,
              
              { transaction }
            );
        }
        
        if (data.expense_category !== undefined) {
            await expense_claims.setExpense_category(
              
              data.expense_category,
              
              { transaction }
            );
        }
        
        if (data.approver !== undefined) {
            await expense_claims.setApprover(
              
              data.approver,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await expense_claims.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return expense_claims;
    }

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

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

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


        return expense_claims;
    }

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

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

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

        await expense_claims.destroy({
            transaction
        });

        return expense_claims;
    }

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

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

        if (!expense_claims) {
            return expense_claims;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.employee = await expense_claims.getEmployee({
            transaction
        });
        
        
        output.expense_category = await expense_claims.getExpense_category({
            transaction
        });
        
        
        output.receipts = await expense_claims.getReceipts({
            transaction
        });
        
        
        output.approver = await expense_claims.getApprover({
            transaction
        });
        
        
        output.organizations = await expense_claims.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.expense_categories,
        as: 'expense_category',
        
        where: filter.expense_category ? {
          [Op.or]: [
            { id: { [Op.in]: filter.expense_category.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.expense_category.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



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

    ];

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

            
            if (filter.currency) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'expense_claims',
                        'currency',
                        filter.currency,
                    ),
                };
            }
            
            if (filter.merchant) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'expense_claims',
                        'merchant',
                        filter.merchant,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'expense_claims',
                        'description',
                        filter.description,
                    ),
                };
            }
            
            if (filter.decision_comment) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'expense_claims',
                        'decision_comment',
                        filter.decision_comment,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    decision_at: {
                    ...where.decision_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.expense_claims.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(
                        'expense_claims',
                        'merchant',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

