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

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

        const requisitions = await db.requisitions.create(
            {
                id: data.id || undefined,
        
        req_number: data.req_number
        ||
        null
            ,
            
        title: data.title
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        quantity: data.quantity
        ||
        null
            ,
            
        estimated_budget_usd: data.estimated_budget_usd
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        estimated_budget_original: data.estimated_budget_original
        ||
        null
            ,
            
        fx_rate_to_usd: data.fx_rate_to_usd
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        approved_at: data.approved_at
        ||
        null
            ,
            
        closed_at: data.closed_at
        ||
        null
            ,
            
        return_reason: data.return_reason
        ||
        null
            ,
            
        reject_reason: data.reject_reason
        ||
        null
            ,
            
        is_high_value: data.is_high_value
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await requisitions.setTenant( data.tenant || null, {
            transaction,
        });
        
        await requisitions.setRequester( data.requester || null, {
            transaction,
        });
        
        await requisitions.setDepartment( data.department || null, {
            transaction,
        });
        
        await requisitions.setProject( data.project || null, {
            transaction,
        });
        
        await requisitions.setBudget_line( data.budget_line || null, {
            transaction,
        });
        
        await requisitions.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return requisitions;
    }
    

    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 requisitionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                req_number: item.req_number
            ||
            null
            ,
            
                title: item.title
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                quantity: item.quantity
            ||
            null
            ,
            
                estimated_budget_usd: item.estimated_budget_usd
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                estimated_budget_original: item.estimated_budget_original
            ||
            null
            ,
            
                fx_rate_to_usd: item.fx_rate_to_usd
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                submitted_at: item.submitted_at
            ||
            null
            ,
            
                approved_at: item.approved_at
            ||
            null
            ,
            
                closed_at: item.closed_at
            ||
            null
            ,
            
                return_reason: item.return_reason
            ||
            null
            ,
            
                reject_reason: item.reject_reason
            ||
            null
            ,
            
                is_high_value: item.is_high_value
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return requisitions;
    }

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


        

        const updatePayload = {};
        
        if (data.req_number !== undefined) updatePayload.req_number = data.req_number;
        
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
        
        
        if (data.estimated_budget_usd !== undefined) updatePayload.estimated_budget_usd = data.estimated_budget_usd;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.estimated_budget_original !== undefined) updatePayload.estimated_budget_original = data.estimated_budget_original;
        
        
        if (data.fx_rate_to_usd !== undefined) updatePayload.fx_rate_to_usd = data.fx_rate_to_usd;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.approved_at !== undefined) updatePayload.approved_at = data.approved_at;
        
        
        if (data.closed_at !== undefined) updatePayload.closed_at = data.closed_at;
        
        
        if (data.return_reason !== undefined) updatePayload.return_reason = data.return_reason;
        
        
        if (data.reject_reason !== undefined) updatePayload.reject_reason = data.reject_reason;
        
        
        if (data.is_high_value !== undefined) updatePayload.is_high_value = data.is_high_value;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await requisitions.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.requester !== undefined) {
            await requisitions.setRequester(
              
              data.requester,
              
              { transaction }
            );
        }
        
        if (data.department !== undefined) {
            await requisitions.setDepartment(
              
              data.department,
              
              { transaction }
            );
        }
        
        if (data.project !== undefined) {
            await requisitions.setProject(
              
              data.project,
              
              { transaction }
            );
        }
        
        if (data.budget_line !== undefined) {
            await requisitions.setBudget_line(
              
              data.budget_line,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await requisitions.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return requisitions;
    }

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

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

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


        return requisitions;
    }

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

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

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

        await requisitions.destroy({
            transaction
        });

        return requisitions;
    }

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

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

        if (!requisitions) {
            return requisitions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        output.approval_steps_requisition = await requisitions.getApproval_steps_requisition({
            transaction
        });
        
        
        output.procurement_cases_requisition = await requisitions.getProcurement_cases_requisition({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.purchase_orders_requisition = await requisitions.getPurchase_orders_requisition({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await requisitions.getTenant({
            transaction
        });
        
        
        output.requester = await requisitions.getRequester({
            transaction
        });
        
        
        output.department = await requisitions.getDepartment({
            transaction
        });
        
        
        output.project = await requisitions.getProject({
            transaction
        });
        
        
        output.budget_line = await requisitions.getBudget_line({
            transaction
        });
        
        
        output.attachments = await requisitions.getAttachments({
            transaction
        });
        
        
        output.organizations = await requisitions.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.tenants,
        as: 'tenant',
        
        where: filter.tenant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        model: db.departments,
        as: 'department',
        
        where: filter.department ? {
          [Op.or]: [
            { id: { [Op.in]: filter.department.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.department.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}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        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.organizations,
        as: 'organizations',
        
      },



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

    ];

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

            
            if (filter.req_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'requisitions',
                        'req_number',
                        filter.req_number,
                    ),
                };
            }
            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'requisitions',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'requisitions',
                        'description',
                        filter.description,
                    ),
                };
            }
            
            if (filter.return_reason) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'requisitions',
                        'return_reason',
                        filter.return_reason,
                    ),
                };
            }
            
            if (filter.reject_reason) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'requisitions',
                        'reject_reason',
                        filter.reject_reason,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    fx_rate_to_usd: {
                    ...where.fx_rate_to_usd,
                            [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.approved_atRange) {
                const [start, end] = filter.approved_atRange;

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    closed_at: {
                    ...where.closed_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.is_high_value) {
                where = {
                    ...where,
                is_high_value: filter.is_high_value,
            };
            }
            


      

      

      

      

      

      
      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.requisitions.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(
                        'requisitions',
                        'req_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

