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

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

        const supplier_offers = await db.supplier_offers.create(
            {
                id: data.id || undefined,
        
        amount: data.amount
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        amount_usd: data.amount_usd
        ||
        null
            ,
            
        delivery_lead_time: data.delivery_lead_time
        ||
        null
            ,
            
        warranty_terms: data.warranty_terms
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        received_at: data.received_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await supplier_offers.setTenant( data.tenant || null, {
            transaction,
        });
        
        await supplier_offers.setProcurement_case( data.procurement_case || null, {
            transaction,
        });
        
        await supplier_offers.setSupplier( data.supplier || null, {
            transaction,
        });
        
        await supplier_offers.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return supplier_offers;
    }
    

    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 supplier_offersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                amount: item.amount
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                amount_usd: item.amount_usd
            ||
            null
            ,
            
                delivery_lead_time: item.delivery_lead_time
            ||
            null
            ,
            
                warranty_terms: item.warranty_terms
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                received_at: item.received_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return supplier_offers;
    }

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


        

        const updatePayload = {};
        
        if (data.amount !== undefined) updatePayload.amount = data.amount;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.amount_usd !== undefined) updatePayload.amount_usd = data.amount_usd;
        
        
        if (data.delivery_lead_time !== undefined) updatePayload.delivery_lead_time = data.delivery_lead_time;
        
        
        if (data.warranty_terms !== undefined) updatePayload.warranty_terms = data.warranty_terms;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.received_at !== undefined) updatePayload.received_at = data.received_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await supplier_offers.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.procurement_case !== undefined) {
            await supplier_offers.setProcurement_case(
              
              data.procurement_case,
              
              { transaction }
            );
        }
        
        if (data.supplier !== undefined) {
            await supplier_offers.setSupplier(
              
              data.supplier,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await supplier_offers.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return supplier_offers;
    }

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

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

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


        return supplier_offers;
    }

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

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

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

        await supplier_offers.destroy({
            transaction
        });

        return supplier_offers;
    }

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

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

        if (!supplier_offers) {
            return supplier_offers;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.offer_scores_supplier_offer = await supplier_offers.getOffer_scores_supplier_offer({
            transaction
        });
        
        
        output.awards_winning_offer = await supplier_offers.getAwards_winning_offer({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await supplier_offers.getTenant({
            transaction
        });
        
        
        output.procurement_case = await supplier_offers.getProcurement_case({
            transaction
        });
        
        
        output.supplier = await supplier_offers.getSupplier({
            transaction
        });
        
        
        output.offer_files = await supplier_offers.getOffer_files({
            transaction
        });
        
        
        output.organizations = await supplier_offers.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.suppliers,
        as: 'supplier',
        
        where: filter.supplier ? {
          [Op.or]: [
            { id: { [Op.in]: filter.supplier.split('|').map(term => Utils.uuid(term)) } },
            {
              legal_name: {
                [Op.or]: filter.supplier.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

    ];

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

            
            if (filter.delivery_lead_time) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'supplier_offers',
                        'delivery_lead_time',
                        filter.delivery_lead_time,
                    ),
                };
            }
            
            if (filter.warranty_terms) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'supplier_offers',
                        'warranty_terms',
                        filter.warranty_terms,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

    
};

