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

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

        const vendors = await db.vendors.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        trade_name: data.trade_name
        ||
        null
            ,
            
        vendor_type: data.vendor_type
        ||
        null
            ,
            
        registration_number: data.registration_number
        ||
        null
            ,
            
        tax_number: data.tax_number
        ||
        null
            ,
            
        contact_name: data.contact_name
        ||
        null
            ,
            
        contact_email: data.contact_email
        ||
        null
            ,
            
        contact_phone: data.contact_phone
        ||
        null
            ,
            
        address: data.address
        ||
        null
            ,
            
        bank_name: data.bank_name
        ||
        null
            ,
            
        bank_account_number: data.bank_account_number
        ||
        null
            ,
            
        bank_account_name: data.bank_account_name
        ||
        null
            ,
            
        bank_swift: data.bank_swift
        ||
        null
            ,
            
        qualification_status: data.qualification_status
        ||
        null
            ,
            
        qualification_reviewed_at: data.qualification_reviewed_at
        ||
        null
            ,
            
        risk_rating: data.risk_rating
        ||
        null
            ,
            
        is_blacklisted: data.is_blacklisted
        ||
        false
        
            ,
            
        compliance_valid_until: data.compliance_valid_until
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await vendors.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        

        

        

        return vendors;
    }
    

    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 vendorsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                trade_name: item.trade_name
            ||
            null
            ,
            
                vendor_type: item.vendor_type
            ||
            null
            ,
            
                registration_number: item.registration_number
            ||
            null
            ,
            
                tax_number: item.tax_number
            ||
            null
            ,
            
                contact_name: item.contact_name
            ||
            null
            ,
            
                contact_email: item.contact_email
            ||
            null
            ,
            
                contact_phone: item.contact_phone
            ||
            null
            ,
            
                address: item.address
            ||
            null
            ,
            
                bank_name: item.bank_name
            ||
            null
            ,
            
                bank_account_number: item.bank_account_number
            ||
            null
            ,
            
                bank_account_name: item.bank_account_name
            ||
            null
            ,
            
                bank_swift: item.bank_swift
            ||
            null
            ,
            
                qualification_status: item.qualification_status
            ||
            null
            ,
            
                qualification_reviewed_at: item.qualification_reviewed_at
            ||
            null
            ,
            
                risk_rating: item.risk_rating
            ||
            null
            ,
            
                is_blacklisted: item.is_blacklisted
            ||
            false
        
            ,
            
                compliance_valid_until: item.compliance_valid_until
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return vendors;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.trade_name !== undefined) updatePayload.trade_name = data.trade_name;
        
        
        if (data.vendor_type !== undefined) updatePayload.vendor_type = data.vendor_type;
        
        
        if (data.registration_number !== undefined) updatePayload.registration_number = data.registration_number;
        
        
        if (data.tax_number !== undefined) updatePayload.tax_number = data.tax_number;
        
        
        if (data.contact_name !== undefined) updatePayload.contact_name = data.contact_name;
        
        
        if (data.contact_email !== undefined) updatePayload.contact_email = data.contact_email;
        
        
        if (data.contact_phone !== undefined) updatePayload.contact_phone = data.contact_phone;
        
        
        if (data.address !== undefined) updatePayload.address = data.address;
        
        
        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_account_name !== undefined) updatePayload.bank_account_name = data.bank_account_name;
        
        
        if (data.bank_swift !== undefined) updatePayload.bank_swift = data.bank_swift;
        
        
        if (data.qualification_status !== undefined) updatePayload.qualification_status = data.qualification_status;
        
        
        if (data.qualification_reviewed_at !== undefined) updatePayload.qualification_reviewed_at = data.qualification_reviewed_at;
        
        
        if (data.risk_rating !== undefined) updatePayload.risk_rating = data.risk_rating;
        
        
        if (data.is_blacklisted !== undefined) updatePayload.is_blacklisted = data.is_blacklisted;
        
        
        if (data.compliance_valid_until !== undefined) updatePayload.compliance_valid_until = data.compliance_valid_until;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await vendors.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        

        
        

        

        return vendors;
    }

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

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

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


        return vendors;
    }

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

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

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

        await vendors.destroy({
            transaction
        });

        return vendors;
    }

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

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

        if (!vendors) {
            return vendors;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.vendor_compliance_documents_vendor = await vendors.getVendor_compliance_documents_vendor({
            transaction
        });
        
        
        output.bids_vendor = await vendors.getBids_vendor({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.contracts_vendor = await vendors.getContracts_vendor({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.invoices_vendor = await vendors.getInvoices_vendor({
            transaction
        });
        
        
        
        
        output.payments_vendor = await vendors.getPayments_vendor({
            transaction
        });
        
        
        
        
        
        
        
        output.organization = await vendors.getOrganization({
            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',
        
      },



    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.trade_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'trade_name',
                        filter.trade_name,
                    ),
                };
            }
            
            if (filter.registration_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'registration_number',
                        filter.registration_number,
                    ),
                };
            }
            
            if (filter.tax_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'tax_number',
                        filter.tax_number,
                    ),
                };
            }
            
            if (filter.contact_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'contact_name',
                        filter.contact_name,
                    ),
                };
            }
            
            if (filter.contact_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'contact_email',
                        filter.contact_email,
                    ),
                };
            }
            
            if (filter.contact_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'contact_phone',
                        filter.contact_phone,
                    ),
                };
            }
            
            if (filter.address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'address',
                        filter.address,
                    ),
                };
            }
            
            if (filter.bank_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'bank_name',
                        filter.bank_name,
                    ),
                };
            }
            
            if (filter.bank_account_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'bank_account_number',
                        filter.bank_account_number,
                    ),
                };
            }
            
            if (filter.bank_account_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'bank_account_name',
                        filter.bank_account_name,
                    ),
                };
            }
            
            if (filter.bank_swift) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'bank_swift',
                        filter.bank_swift,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.vendor_type) {
                where = {
                    ...where,
                vendor_type: filter.vendor_type,
            };
            }
            
            if (filter.qualification_status) {
                where = {
                    ...where,
                qualification_status: filter.qualification_status,
            };
            }
            
            if (filter.risk_rating) {
                where = {
                    ...where,
                risk_rating: filter.risk_rating,
            };
            }
            
            if (filter.is_blacklisted) {
                where = {
                    ...where,
                is_blacklisted: filter.is_blacklisted,
            };
            }
            


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

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

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

    
};

