
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,
        
        requisition_number: data.requisition_number
        ||
        null
            ,
            
        title: data.title
        ||
        null
            ,
            
        scope_of_work: data.scope_of_work
        ||
        null
            ,
            
        procurement_method: data.procurement_method
        ||
        null
            ,
            
        estimated_amount: data.estimated_amount
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        needed_by_date: data.needed_by_date
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        rejection_reason: data.rejection_reason
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await requisitions.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await requisitions.setProcurement_plan( data.procurement_plan || null, {
            transaction,
        });
        
        await requisitions.setRequesting_department( data.requesting_department || null, {
            transaction,
        });
        
        await requisitions.setBudget_line( data.budget_line || null, {
            transaction,
        });
        
        await requisitions.setProvince( data.province || null, {
            transaction,
        });
        
        await requisitions.setRequested_by_user( data.requested_by_user || null, {
            transaction,
        });
        

        

        

        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,
                
                requisition_number: item.requisition_number
            ||
            null
            ,
            
                title: item.title
            ||
            null
            ,
            
                scope_of_work: item.scope_of_work
            ||
            null
            ,
            
                procurement_method: item.procurement_method
            ||
            null
            ,
            
                estimated_amount: item.estimated_amount
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                needed_by_date: item.needed_by_date
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                submitted_at: item.submitted_at
            ||
            null
            ,
            
                rejection_reason: item.rejection_reason
            ||
            null
            ,
            
            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
        

        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.requisition_number !== undefined) updatePayload.requisition_number = data.requisition_number;
        
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.scope_of_work !== undefined) updatePayload.scope_of_work = data.scope_of_work;
        
        
        if (data.procurement_method !== undefined) updatePayload.procurement_method = data.procurement_method;
        
        
        if (data.estimated_amount !== undefined) updatePayload.estimated_amount = data.estimated_amount;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.needed_by_date !== undefined) updatePayload.needed_by_date = data.needed_by_date;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.rejection_reason !== undefined) updatePayload.rejection_reason = data.rejection_reason;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await requisitions.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.procurement_plan !== undefined) {
            await requisitions.setProcurement_plan(
              
              data.procurement_plan,
              
              { transaction }
            );
        }
        
        if (data.requesting_department !== undefined) {
            await requisitions.setRequesting_department(
              
              data.requesting_department,
              
              { transaction }
            );
        }
        
        if (data.budget_line !== undefined) {
            await requisitions.setBudget_line(
              
              data.budget_line,
              
              { transaction }
            );
        }
        
        if (data.province !== undefined) {
            await requisitions.setProvince(
              
              data.province,
              
              { transaction }
            );
        }
        
        if (data.requested_by_user !== undefined) {
            await requisitions.setRequested_by_user(
              
              data.requested_by_user,
              
              { transaction }
            );
        }
        

        
        

        

        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.tenders_requisition = await requisitions.getTenders_requisition({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await requisitions.getOrganization({
            transaction
        });
        
        
        output.procurement_plan = await requisitions.getProcurement_plan({
            transaction
        });
        
        
        output.requesting_department = await requisitions.getRequesting_department({
            transaction
        });
        
        
        output.budget_line = await requisitions.getBudget_line({
            transaction
        });
        
        
        output.province = await requisitions.getProvince({
            transaction
        });
        
        
        output.requested_by_user = await requisitions.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.procurement_plans,
        as: 'procurement_plan',
        
        where: filter.procurement_plan ? {
          [Op.or]: [
            { id: { [Op.in]: filter.procurement_plan.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.procurement_plan.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.departments,
        as: 'requesting_department',
        
        where: filter.requesting_department ? {
          [Op.or]: [
            { id: { [Op.in]: filter.requesting_department.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.requesting_department.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.provinces,
        as: 'province',
        
        where: filter.province ? {
          [Op.or]: [
            { id: { [Op.in]: filter.province.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.province.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.requisition_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'requisitions',
                        'requisition_number',
                        filter.requisition_number,
                    ),
                };
            }
            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'requisitions',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.scope_of_work) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'requisitions',
                        'scope_of_work',
                        filter.scope_of_work,
                    ),
                };
            }
            
            if (filter.rejection_reason) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'requisitions',
                        'rejection_reason',
                        filter.rejection_reason,
                    ),
                };
            }
            

            
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    needed_by_date: {
                    ...where.needed_by_date,
                            [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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.procurement_method) {
                where = {
                    ...where,
                procurement_method: filter.procurement_method,
            };
            }
            
            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.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',
                        'requisition_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

