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

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

        const obligations = await db.obligations.create(
            {
                id: data.id || undefined,
        
        obligation_number: data.obligation_number
        ||
        null
            ,
            
        amount: data.amount
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        obligated_at: data.obligated_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await obligations.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await obligations.setBudget_line( data.budget_line || null, {
            transaction,
        });
        
        await obligations.setContract( data.contract || null, {
            transaction,
        });
        
        await obligations.setProject( data.project || null, {
            transaction,
        });
        

        

        

        return obligations;
    }
    

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

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

        // For each item created, replace relation files
        

        return obligations;
    }

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


        

        const updatePayload = {};
        
        if (data.obligation_number !== undefined) updatePayload.obligation_number = data.obligation_number;
        
        
        if (data.amount !== undefined) updatePayload.amount = data.amount;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.obligated_at !== undefined) updatePayload.obligated_at = data.obligated_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await obligations.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.budget_line !== undefined) {
            await obligations.setBudget_line(
              
              data.budget_line,
              
              { transaction }
            );
        }
        
        if (data.contract !== undefined) {
            await obligations.setContract(
              
              data.contract,
              
              { transaction }
            );
        }
        
        if (data.project !== undefined) {
            await obligations.setProject(
              
              data.project,
              
              { transaction }
            );
        }
        

        
        

        

        return obligations;
    }

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

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

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


        return obligations;
    }

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

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

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

        await obligations.destroy({
            transaction
        });

        return obligations;
    }

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

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

        if (!obligations) {
            return obligations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await obligations.getOrganization({
            transaction
        });
        
        
        output.budget_line = await obligations.getBudget_line({
            transaction
        });
        
        
        output.contract = await obligations.getContract({
            transaction
        });
        
        
        output.project = await obligations.getProject({
            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.budget_lines,
        as: 'budget_line',
        
        where: filter.budget_line ? {
          [Op.or]: [
            { id: { [Op.in]: filter.budget_line.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.budget_line.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            
            if (filter.obligation_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'obligations',
                        'obligation_number',
                        filter.obligation_number,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'obligations',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    obligated_at: {
                    ...where.obligated_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.obligations.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(
                        'obligations',
                        'obligation_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

