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

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

        const suppliers = await db.suppliers.create(
            {
                id: data.id || undefined,
        
        legal_name: data.legal_name
        ||
        null
            ,
            
        commercial_name: data.commercial_name
        ||
        null
            ,
            
        rccm_number: data.rccm_number
        ||
        null
            ,
            
        tax_id: data.tax_id
        ||
        null
            ,
            
        country: data.country
        ||
        null
            ,
            
        address: data.address
        ||
        null
            ,
            
        primary_contact_name: data.primary_contact_name
        ||
        null
            ,
            
        primary_contact_email: data.primary_contact_email
        ||
        null
            ,
            
        primary_contact_phone: data.primary_contact_phone
        ||
        null
            ,
            
        bank_name: data.bank_name
        ||
        null
            ,
            
        bank_account_number: data.bank_account_number
        ||
        null
            ,
            
        bank_swift: data.bank_swift
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        prequalification_status: data.prequalification_status
        ||
        null
            ,
            
        performance_score: data.performance_score
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await suppliers.setTenant( data.tenant || null, {
            transaction,
        });
        
        await suppliers.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return suppliers;
    }
    

    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 suppliersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                legal_name: item.legal_name
            ||
            null
            ,
            
                commercial_name: item.commercial_name
            ||
            null
            ,
            
                rccm_number: item.rccm_number
            ||
            null
            ,
            
                tax_id: item.tax_id
            ||
            null
            ,
            
                country: item.country
            ||
            null
            ,
            
                address: item.address
            ||
            null
            ,
            
                primary_contact_name: item.primary_contact_name
            ||
            null
            ,
            
                primary_contact_email: item.primary_contact_email
            ||
            null
            ,
            
                primary_contact_phone: item.primary_contact_phone
            ||
            null
            ,
            
                bank_name: item.bank_name
            ||
            null
            ,
            
                bank_account_number: item.bank_account_number
            ||
            null
            ,
            
                bank_swift: item.bank_swift
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                prequalification_status: item.prequalification_status
            ||
            null
            ,
            
                performance_score: item.performance_score
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return suppliers;
    }

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


        

        const updatePayload = {};
        
        if (data.legal_name !== undefined) updatePayload.legal_name = data.legal_name;
        
        
        if (data.commercial_name !== undefined) updatePayload.commercial_name = data.commercial_name;
        
        
        if (data.rccm_number !== undefined) updatePayload.rccm_number = data.rccm_number;
        
        
        if (data.tax_id !== undefined) updatePayload.tax_id = data.tax_id;
        
        
        if (data.country !== undefined) updatePayload.country = data.country;
        
        
        if (data.address !== undefined) updatePayload.address = data.address;
        
        
        if (data.primary_contact_name !== undefined) updatePayload.primary_contact_name = data.primary_contact_name;
        
        
        if (data.primary_contact_email !== undefined) updatePayload.primary_contact_email = data.primary_contact_email;
        
        
        if (data.primary_contact_phone !== undefined) updatePayload.primary_contact_phone = data.primary_contact_phone;
        
        
        if (data.bank_name !== undefined) updatePayload.bank_name = data.bank_name;
        
        
        if (data.bank_account_number !== undefined) updatePayload.bank_account_number = data.bank_account_number;
        
        
        if (data.bank_swift !== undefined) updatePayload.bank_swift = data.bank_swift;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.prequalification_status !== undefined) updatePayload.prequalification_status = data.prequalification_status;
        
        
        if (data.performance_score !== undefined) updatePayload.performance_score = data.performance_score;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await suppliers.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await suppliers.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return suppliers;
    }

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

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

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


        return suppliers;
    }

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

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

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

        await suppliers.destroy({
            transaction
        });

        return suppliers;
    }

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

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

        if (!suppliers) {
            return suppliers;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.supplier_diligence_checks_supplier = await suppliers.getSupplier_diligence_checks_supplier({
            transaction
        });
        
        
        
        output.supplier_offers_supplier = await suppliers.getSupplier_offers_supplier({
            transaction
        });
        
        
        
        
        output.awards_awarded_supplier = await suppliers.getAwards_awarded_supplier({
            transaction
        });
        
        
        output.purchase_orders_supplier = await suppliers.getPurchase_orders_supplier({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await suppliers.getTenant({
            transaction
        });
        
        
        output.documents = await suppliers.getDocuments({
            transaction
        });
        
        
        output.organizations = await suppliers.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.organizations,
        as: 'organizations',
        
      },



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

    ];

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

            
            if (filter.legal_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'suppliers',
                        'legal_name',
                        filter.legal_name,
                    ),
                };
            }
            
            if (filter.commercial_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'suppliers',
                        'commercial_name',
                        filter.commercial_name,
                    ),
                };
            }
            
            if (filter.rccm_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'suppliers',
                        'rccm_number',
                        filter.rccm_number,
                    ),
                };
            }
            
            if (filter.tax_id) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'suppliers',
                        'tax_id',
                        filter.tax_id,
                    ),
                };
            }
            
            if (filter.address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'suppliers',
                        'address',
                        filter.address,
                    ),
                };
            }
            
            if (filter.primary_contact_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'suppliers',
                        'primary_contact_name',
                        filter.primary_contact_name,
                    ),
                };
            }
            
            if (filter.primary_contact_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'suppliers',
                        'primary_contact_email',
                        filter.primary_contact_email,
                    ),
                };
            }
            
            if (filter.primary_contact_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'suppliers',
                        'primary_contact_phone',
                        filter.primary_contact_phone,
                    ),
                };
            }
            
            if (filter.bank_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'suppliers',
                        'bank_name',
                        filter.bank_name,
                    ),
                };
            }
            
            if (filter.bank_account_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'suppliers',
                        'bank_account_number',
                        filter.bank_account_number,
                    ),
                };
            }
            
            if (filter.bank_swift) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'suppliers',
                        'bank_swift',
                        filter.bank_swift,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.country) {
                where = {
                    ...where,
                country: filter.country,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.prequalification_status) {
                where = {
                    ...where,
                prequalification_status: filter.prequalification_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.suppliers.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(
                        'suppliers',
                        'legal_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

