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

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

        const bid_evaluations = await db.bid_evaluations.create(
            {
                id: data.id || undefined,
        
        technical_score: data.technical_score
        ||
        null
            ,
            
        financial_score: data.financial_score
        ||
        null
            ,
            
        total_score: data.total_score
        ||
        null
            ,
            
        recommendation: data.recommendation
        ||
        null
            ,
            
        justification: data.justification
        ||
        null
            ,
            
        evaluated_at: data.evaluated_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await bid_evaluations.setBid( data.bid || null, {
            transaction,
        });
        
        await bid_evaluations.setLead_evaluator_user( data.lead_evaluator_user || null, {
            transaction,
        });
        
        await bid_evaluations.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return bid_evaluations;
    }
    

    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 bid_evaluationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                technical_score: item.technical_score
            ||
            null
            ,
            
                financial_score: item.financial_score
            ||
            null
            ,
            
                total_score: item.total_score
            ||
            null
            ,
            
                recommendation: item.recommendation
            ||
            null
            ,
            
                justification: item.justification
            ||
            null
            ,
            
                evaluated_at: item.evaluated_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return bid_evaluations;
    }

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


        

        const updatePayload = {};
        
        if (data.technical_score !== undefined) updatePayload.technical_score = data.technical_score;
        
        
        if (data.financial_score !== undefined) updatePayload.financial_score = data.financial_score;
        
        
        if (data.total_score !== undefined) updatePayload.total_score = data.total_score;
        
        
        if (data.recommendation !== undefined) updatePayload.recommendation = data.recommendation;
        
        
        if (data.justification !== undefined) updatePayload.justification = data.justification;
        
        
        if (data.evaluated_at !== undefined) updatePayload.evaluated_at = data.evaluated_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.bid !== undefined) {
            await bid_evaluations.setBid(
              
              data.bid,
              
              { transaction }
            );
        }
        
        if (data.lead_evaluator_user !== undefined) {
            await bid_evaluations.setLead_evaluator_user(
              
              data.lead_evaluator_user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await bid_evaluations.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return bid_evaluations;
    }

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

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

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


        return bid_evaluations;
    }

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

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

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

        await bid_evaluations.destroy({
            transaction
        });

        return bid_evaluations;
    }

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

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

        if (!bid_evaluations) {
            return bid_evaluations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.bid = await bid_evaluations.getBid({
            transaction
        });
        
        
        output.lead_evaluator_user = await bid_evaluations.getLead_evaluator_user({
            transaction
        });
        
        
        output.organizations = await bid_evaluations.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.bids,
        as: 'bid',
        
        where: filter.bid ? {
          [Op.or]: [
            { id: { [Op.in]: filter.bid.split('|').map(term => Utils.uuid(term)) } },
            {
              bid_reference: {
                [Op.or]: filter.bid.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

            
            

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

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

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

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

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

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

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

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

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

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

            
            if (filter.recommendation) {
                where = {
                    ...where,
                recommendation: filter.recommendation,
            };
            }
            


      

      

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

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

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

    
};

