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

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

        const budget_reallocations = await db.budget_reallocations.create(
            {
                id: data.id || undefined,
        
        amount: data.amount
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        requested_at: data.requested_at
        ||
        null
            ,
            
        justification: data.justification
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await budget_reallocations.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await budget_reallocations.setFiscal_year( data.fiscal_year || null, {
            transaction,
        });
        
        await budget_reallocations.setFrom_budget_line( data.from_budget_line || null, {
            transaction,
        });
        
        await budget_reallocations.setTo_budget_line( data.to_budget_line || null, {
            transaction,
        });
        
        await budget_reallocations.setRequested_by_user( data.requested_by_user || null, {
            transaction,
        });
        

        

        

        return budget_reallocations;
    }
    

    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 budget_reallocationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                amount: item.amount
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                requested_at: item.requested_at
            ||
            null
            ,
            
                justification: item.justification
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return budget_reallocations;
    }

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


        

        const updatePayload = {};
        
        if (data.amount !== undefined) updatePayload.amount = data.amount;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
        
        
        if (data.justification !== undefined) updatePayload.justification = data.justification;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await budget_reallocations.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.fiscal_year !== undefined) {
            await budget_reallocations.setFiscal_year(
              
              data.fiscal_year,
              
              { transaction }
            );
        }
        
        if (data.from_budget_line !== undefined) {
            await budget_reallocations.setFrom_budget_line(
              
              data.from_budget_line,
              
              { transaction }
            );
        }
        
        if (data.to_budget_line !== undefined) {
            await budget_reallocations.setTo_budget_line(
              
              data.to_budget_line,
              
              { transaction }
            );
        }
        
        if (data.requested_by_user !== undefined) {
            await budget_reallocations.setRequested_by_user(
              
              data.requested_by_user,
              
              { transaction }
            );
        }
        

        
        

        

        return budget_reallocations;
    }

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

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

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


        return budget_reallocations;
    }

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

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

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

        await budget_reallocations.destroy({
            transaction
        });

        return budget_reallocations;
    }

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

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

        if (!budget_reallocations) {
            return budget_reallocations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await budget_reallocations.getOrganization({
            transaction
        });
        
        
        output.fiscal_year = await budget_reallocations.getFiscal_year({
            transaction
        });
        
        
        output.from_budget_line = await budget_reallocations.getFrom_budget_line({
            transaction
        });
        
        
        output.to_budget_line = await budget_reallocations.getTo_budget_line({
            transaction
        });
        
        
        output.requested_by_user = await budget_reallocations.getRequested_by_user({
            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.organizations,
        as: 'organization',
        
      },

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

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

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

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



    ];

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

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

            
            

            
            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.requested_atRange) {
                const [start, end] = filter.requested_atRange;

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

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

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

            
            if (filter.currency) {
                where = {
                    ...where,
                currency: filter.currency,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      
      if (filter.organization) {
        const listItems = filter.organization.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationId: {[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.budget_reallocations.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(
                        'budget_reallocations',
                        'justification',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

