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

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

        const awards = await db.awards.create(
            {
                id: data.id || undefined,
        
        awarded_amount_usd: data.awarded_amount_usd
        ||
        null
            ,
            
        award_rationale: data.award_rationale
        ||
        null
            ,
            
        awarded_at: data.awarded_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await awards.setTenant( data.tenant || null, {
            transaction,
        });
        
        await awards.setProcurement_case( data.procurement_case || null, {
            transaction,
        });
        
        await awards.setWinning_offer( data.winning_offer || null, {
            transaction,
        });
        
        await awards.setAwarded_supplier( data.awarded_supplier || null, {
            transaction,
        });
        
        await awards.setAwarded_by( data.awarded_by || null, {
            transaction,
        });
        
        await awards.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return awards;
    }
    

    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 awardsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                awarded_amount_usd: item.awarded_amount_usd
            ||
            null
            ,
            
                award_rationale: item.award_rationale
            ||
            null
            ,
            
                awarded_at: item.awarded_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return awards;
    }

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


        

        const updatePayload = {};
        
        if (data.awarded_amount_usd !== undefined) updatePayload.awarded_amount_usd = data.awarded_amount_usd;
        
        
        if (data.award_rationale !== undefined) updatePayload.award_rationale = data.award_rationale;
        
        
        if (data.awarded_at !== undefined) updatePayload.awarded_at = data.awarded_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await awards.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.procurement_case !== undefined) {
            await awards.setProcurement_case(
              
              data.procurement_case,
              
              { transaction }
            );
        }
        
        if (data.winning_offer !== undefined) {
            await awards.setWinning_offer(
              
              data.winning_offer,
              
              { transaction }
            );
        }
        
        if (data.awarded_supplier !== undefined) {
            await awards.setAwarded_supplier(
              
              data.awarded_supplier,
              
              { transaction }
            );
        }
        
        if (data.awarded_by !== undefined) {
            await awards.setAwarded_by(
              
              data.awarded_by,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await awards.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return awards;
    }

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

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

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


        return awards;
    }

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

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

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

        await awards.destroy({
            transaction
        });

        return awards;
    }

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

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

        if (!awards) {
            return awards;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await awards.getTenant({
            transaction
        });
        
        
        output.procurement_case = await awards.getProcurement_case({
            transaction
        });
        
        
        output.winning_offer = await awards.getWinning_offer({
            transaction
        });
        
        
        output.awarded_supplier = await awards.getAwarded_supplier({
            transaction
        });
        
        
        output.awarded_by = await awards.getAwarded_by({
            transaction
        });
        
        
        output.award_documents = await awards.getAward_documents({
            transaction
        });
        
        
        output.organizations = await awards.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.procurement_cases,
        as: 'procurement_case',
        
        where: filter.procurement_case ? {
          [Op.or]: [
            { id: { [Op.in]: filter.procurement_case.split('|').map(term => Utils.uuid(term)) } },
            {
              pipeline_stage: {
                [Op.or]: filter.procurement_case.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



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

    ];

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

            
            if (filter.award_rationale) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'awards',
                        'award_rationale',
                        filter.award_rationale,
                    ),
                };
            }
            

            
            

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

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

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

            


      

      

      

      

      

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

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

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

    
};

