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

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

        const budget_lines = await db.budget_lines.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        code: data.code
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        category: data.category
        ||
        null
            ,
            
        approved_amount: data.approved_amount
        ||
        null
            ,
            
        committed_amount: data.committed_amount
        ||
        null
            ,
            
        disbursed_amount: data.disbursed_amount
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await budget_lines.setBudget_program( data.budget_program || null, {
            transaction,
        });
        
        await budget_lines.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return budget_lines;
    }
    

    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_linesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                code: item.code
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                category: item.category
            ||
            null
            ,
            
                approved_amount: item.approved_amount
            ||
            null
            ,
            
                committed_amount: item.committed_amount
            ||
            null
            ,
            
                disbursed_amount: item.disbursed_amount
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return budget_lines;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.code !== undefined) updatePayload.code = data.code;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.category !== undefined) updatePayload.category = data.category;
        
        
        if (data.approved_amount !== undefined) updatePayload.approved_amount = data.approved_amount;
        
        
        if (data.committed_amount !== undefined) updatePayload.committed_amount = data.committed_amount;
        
        
        if (data.disbursed_amount !== undefined) updatePayload.disbursed_amount = data.disbursed_amount;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.budget_program !== undefined) {
            await budget_lines.setBudget_program(
              
              data.budget_program,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await budget_lines.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return budget_lines;
    }

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

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

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


        return budget_lines;
    }

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

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

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

        await budget_lines.destroy({
            transaction
        });

        return budget_lines;
    }

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

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

        if (!budget_lines) {
            return budget_lines;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.allocations_budget_line = await budget_lines.getAllocations_budget_line({
            transaction
        });
        
        
        output.budget_reallocations_from_budget_line = await budget_lines.getBudget_reallocations_from_budget_line({
            transaction
        });
        
        output.budget_reallocations_to_budget_line = await budget_lines.getBudget_reallocations_to_budget_line({
            transaction
        });
        
        
        
        output.requisitions_budget_line = await budget_lines.getRequisitions_budget_line({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.projects_budget_line = await budget_lines.getProjects_budget_line({
            transaction
        });
        
        
        
        
        
        
        output.contracts_budget_line = await budget_lines.getContracts_budget_line({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.obligations_budget_line = await budget_lines.getObligations_budget_line({
            transaction
        });
        
        
        
        
        
        
        output.budget_program = await budget_lines.getBudget_program({
            transaction
        });
        
        
        output.organizations = await budget_lines.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.budget_programs,
        as: 'budget_program',
        
        where: filter.budget_program ? {
          [Op.or]: [
            { id: { [Op.in]: filter.budget_program.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.budget_program.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.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'budget_lines',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'budget_lines',
                        'code',
                        filter.code,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'budget_lines',
                        'description',
                        filter.description,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.category) {
                where = {
                    ...where,
                category: filter.category,
            };
            }
            
            if (filter.currency) {
                where = {
                    ...where,
                currency: filter.currency,
            };
            }
            
            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.budget_lines.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_lines',
                        'name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

