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

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

        const bids = await db.bids.create(
            {
                id: data.id || undefined,
        
        bid_reference: data.bid_reference
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        bid_amount: data.bid_amount
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await bids.setTender( data.tender || null, {
            transaction,
        });
        
        await bids.setVendor( data.vendor || null, {
            transaction,
        });
        
        await bids.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return bids;
    }
    

    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 bidsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                bid_reference: item.bid_reference
            ||
            null
            ,
            
                submitted_at: item.submitted_at
            ||
            null
            ,
            
                bid_amount: item.bid_amount
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return bids;
    }

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


        

        const updatePayload = {};
        
        if (data.bid_reference !== undefined) updatePayload.bid_reference = data.bid_reference;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.bid_amount !== undefined) updatePayload.bid_amount = data.bid_amount;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tender !== undefined) {
            await bids.setTender(
              
              data.tender,
              
              { transaction }
            );
        }
        
        if (data.vendor !== undefined) {
            await bids.setVendor(
              
              data.vendor,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await bids.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return bids;
    }

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

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

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


        return bids;
    }

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

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

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

        await bids.destroy({
            transaction
        });

        return bids;
    }

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

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

        if (!bids) {
            return bids;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.bid_evaluations_bid = await bids.getBid_evaluations_bid({
            transaction
        });
        
        
        output.awards_winning_bid = await bids.getAwards_winning_bid({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tender = await bids.getTender({
            transaction
        });
        
        
        output.vendor = await bids.getVendor({
            transaction
        });
        
        
        output.organizations = await bids.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.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.vendors,
        as: 'vendor',
        
        where: filter.vendor ? {
          [Op.or]: [
            { id: { [Op.in]: filter.vendor.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.vendor.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.bid_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'bids',
                        'bid_reference',
                        filter.bid_reference,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'bids',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

            
            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.bid_amountRange) {
                const [start, end] = filter.bid_amountRange;

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

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

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

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

    
};

