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

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

        const procurement_cases = await db.procurement_cases.create(
            {
                id: data.id || undefined,
        
        classification: data.classification
        ||
        null
            ,
            
        classification_justification: data.classification_justification
        ||
        null
            ,
            
        pipeline_stage: data.pipeline_stage
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        sla_due_at: data.sla_due_at
        ||
        null
            ,
            
        awarded_at: data.awarded_at
        ||
        null
            ,
            
        closed_at: data.closed_at
        ||
        null
            ,
            
        admin_override_single_source: data.admin_override_single_source
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await procurement_cases.setTenant( data.tenant || null, {
            transaction,
        });
        
        await procurement_cases.setRequisition( data.requisition || null, {
            transaction,
        });
        
        await procurement_cases.setOwner( data.owner || null, {
            transaction,
        });
        
        await procurement_cases.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return procurement_cases;
    }
    

    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 procurement_casesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                classification: item.classification
            ||
            null
            ,
            
                classification_justification: item.classification_justification
            ||
            null
            ,
            
                pipeline_stage: item.pipeline_stage
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                sla_due_at: item.sla_due_at
            ||
            null
            ,
            
                awarded_at: item.awarded_at
            ||
            null
            ,
            
                closed_at: item.closed_at
            ||
            null
            ,
            
                admin_override_single_source: item.admin_override_single_source
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return procurement_cases;
    }

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


        

        const updatePayload = {};
        
        if (data.classification !== undefined) updatePayload.classification = data.classification;
        
        
        if (data.classification_justification !== undefined) updatePayload.classification_justification = data.classification_justification;
        
        
        if (data.pipeline_stage !== undefined) updatePayload.pipeline_stage = data.pipeline_stage;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.sla_due_at !== undefined) updatePayload.sla_due_at = data.sla_due_at;
        
        
        if (data.awarded_at !== undefined) updatePayload.awarded_at = data.awarded_at;
        
        
        if (data.closed_at !== undefined) updatePayload.closed_at = data.closed_at;
        
        
        if (data.admin_override_single_source !== undefined) updatePayload.admin_override_single_source = data.admin_override_single_source;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await procurement_cases.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.requisition !== undefined) {
            await procurement_cases.setRequisition(
              
              data.requisition,
              
              { transaction }
            );
        }
        
        if (data.owner !== undefined) {
            await procurement_cases.setOwner(
              
              data.owner,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await procurement_cases.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return procurement_cases;
    }

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

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

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


        return procurement_cases;
    }

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

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

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

        await procurement_cases.destroy({
            transaction
        });

        return procurement_cases;
    }

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

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

        if (!procurement_cases) {
            return procurement_cases;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tender_events_procurement_case = await procurement_cases.getTender_events_procurement_case({
            transaction
        });
        
        
        output.supplier_offers_procurement_case = await procurement_cases.getSupplier_offers_procurement_case({
            transaction
        });
        
        
        output.bid_criteria_procurement_case = await procurement_cases.getBid_criteria_procurement_case({
            transaction
        });
        
        
        
        output.awards_procurement_case = await procurement_cases.getAwards_procurement_case({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await procurement_cases.getTenant({
            transaction
        });
        
        
        output.requisition = await procurement_cases.getRequisition({
            transaction
        });
        
        
        output.owner = await procurement_cases.getOwner({
            transaction
        });
        
        
        output.organizations = await procurement_cases.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.requisitions,
        as: 'requisition',
        
        where: filter.requisition ? {
          [Op.or]: [
            { id: { [Op.in]: filter.requisition.split('|').map(term => Utils.uuid(term)) } },
            {
              req_number: {
                [Op.or]: filter.requisition.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.users,
        as: 'owner',
        
        where: filter.owner ? {
          [Op.or]: [
            { id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.owner.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.classification_justification) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'procurement_cases',
                        'classification_justification',
                        filter.classification_justification,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    awarded_at: {
                    ...where.awarded_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.classification) {
                where = {
                    ...where,
                classification: filter.classification,
            };
            }
            
            if (filter.pipeline_stage) {
                where = {
                    ...where,
                pipeline_stage: filter.pipeline_stage,
            };
            }
            
            if (filter.admin_override_single_source) {
                where = {
                    ...where,
                admin_override_single_source: filter.admin_override_single_source,
            };
            }
            


      

      

      

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

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

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

    
};

