
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,
        
        award_number: data.award_number
        ||
        null
            ,
            
        award_amount: data.award_amount
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        decision_date: data.decision_date
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        award_memo: data.award_memo
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await awards.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await awards.setTender( data.tender || null, {
            transaction,
        });
        
        await awards.setWinning_bid( data.winning_bid || null, {
            transaction,
        });
        

        

        

        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,
                
                award_number: item.award_number
            ||
            null
            ,
            
                award_amount: item.award_amount
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                decision_date: item.decision_date
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                award_memo: item.award_memo
            ||
            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
        

        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.award_number !== undefined) updatePayload.award_number = data.award_number;
        
        
        if (data.award_amount !== undefined) updatePayload.award_amount = data.award_amount;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.decision_date !== undefined) updatePayload.decision_date = data.decision_date;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.award_memo !== undefined) updatePayload.award_memo = data.award_memo;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await awards.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.tender !== undefined) {
            await awards.setTender(
              
              data.tender,
              
              { transaction }
            );
        }
        
        if (data.winning_bid !== undefined) {
            await awards.setWinning_bid(
              
              data.winning_bid,
              
              { transaction }
            );
        }
        

        
        

        

        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.contracts_award = await awards.getContracts_award({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await awards.getOrganization({
            transaction
        });
        
        
        output.tender = await awards.getTender({
            transaction
        });
        
        
        output.winning_bid = await awards.getWinning_bid({
            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.tenders,
        as: 'tender',
        
        where: filter.tender ? {
          [Op.or]: [
            { id: { [Op.in]: filter.tender.split('|').map(term => Utils.uuid(term)) } },
            {
              tender_number: {
                [Op.or]: filter.tender.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

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

            
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    decision_date: {
                    ...where.decision_date,
                            [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.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.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_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

