
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,
        
        type: data.type
        ||
        null
            ,
            
        name: data.name
        ||
        null
            ,
            
        legal_name: data.legal_name
        ||
        null
            ,
            
        tax_number: data.tax_number
        ||
        null
            ,
            
        vat_number: data.vat_number
        ||
        null
            ,
            
        iban: data.iban
        ||
        null
            ,
            
        bank_name: data.bank_name
        ||
        null
            ,
            
        email: data.email
        ||
        null
            ,
            
        phone: data.phone
        ||
        null
            ,
            
        phone2: data.phone2
        ||
        null
            ,
            
        website: data.website
        ||
        null
            ,
            
        address_line1: data.address_line1
        ||
        null
            ,
            
        address_line2: data.address_line2
        ||
        null
            ,
            
        postal_code: data.postal_code
        ||
        null
            ,
            
        city: data.city
        ||
        null
            ,
            
        country_code: data.country_code
        ||
        null
            ,
            
        contact_person: data.contact_person
        ||
        null
            ,
            
        contact_email: data.contact_email
        ||
        null
            ,
            
        contact_phone: data.contact_phone
        ||
        null
            ,
            
        contract_number: data.contract_number
        ||
        null
            ,
            
        contract_valid_to: data.contract_valid_to
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await vendors.setCompany( data.company || null, {
            transaction,
        });
        

        

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

        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,
                
                type: item.type
            ||
            null
            ,
            
                name: item.name
            ||
            null
            ,
            
                legal_name: item.legal_name
            ||
            null
            ,
            
                tax_number: item.tax_number
            ||
            null
            ,
            
                vat_number: item.vat_number
            ||
            null
            ,
            
                iban: item.iban
            ||
            null
            ,
            
                bank_name: item.bank_name
            ||
            null
            ,
            
                email: item.email
            ||
            null
            ,
            
                phone: item.phone
            ||
            null
            ,
            
                phone2: item.phone2
            ||
            null
            ,
            
                website: item.website
            ||
            null
            ,
            
                address_line1: item.address_line1
            ||
            null
            ,
            
                address_line2: item.address_line2
            ||
            null
            ,
            
                postal_code: item.postal_code
            ||
            null
            ,
            
                city: item.city
            ||
            null
            ,
            
                country_code: item.country_code
            ||
            null
            ,
            
                contact_person: item.contact_person
            ||
            null
            ,
            
                contact_email: item.contact_email
            ||
            null
            ,
            
                contact_phone: item.contact_phone
            ||
            null
            ,
            
                contract_number: item.contract_number
            ||
            null
            ,
            
                contract_valid_to: item.contract_valid_to
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            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
        
        for (let i = 0; i < vendors.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.vendors.getTableName(),
                    belongsToColumn: 'logo',
                    belongsToId: vendors[i].id,
                },
                data[i].logo,
                options,
            );
        }
        

        return vendors;
    }

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

        const vendors = await db.vendors.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.type !== undefined) updatePayload.type = data.type;
        
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.legal_name !== undefined) updatePayload.legal_name = data.legal_name;
        
        
        if (data.tax_number !== undefined) updatePayload.tax_number = data.tax_number;
        
        
        if (data.vat_number !== undefined) updatePayload.vat_number = data.vat_number;
        
        
        if (data.iban !== undefined) updatePayload.iban = data.iban;
        
        
        if (data.bank_name !== undefined) updatePayload.bank_name = data.bank_name;
        
        
        if (data.email !== undefined) updatePayload.email = data.email;
        
        
        if (data.phone !== undefined) updatePayload.phone = data.phone;
        
        
        if (data.phone2 !== undefined) updatePayload.phone2 = data.phone2;
        
        
        if (data.website !== undefined) updatePayload.website = data.website;
        
        
        if (data.address_line1 !== undefined) updatePayload.address_line1 = data.address_line1;
        
        
        if (data.address_line2 !== undefined) updatePayload.address_line2 = data.address_line2;
        
        
        if (data.postal_code !== undefined) updatePayload.postal_code = data.postal_code;
        
        
        if (data.city !== undefined) updatePayload.city = data.city;
        
        
        if (data.country_code !== undefined) updatePayload.country_code = data.country_code;
        
        
        if (data.contact_person !== undefined) updatePayload.contact_person = data.contact_person;
        
        
        if (data.contact_email !== undefined) updatePayload.contact_email = data.contact_email;
        
        
        if (data.contact_phone !== undefined) updatePayload.contact_phone = data.contact_phone;
        
        
        if (data.contract_number !== undefined) updatePayload.contract_number = data.contract_number;
        
        
        if (data.contract_valid_to !== undefined) updatePayload.contract_valid_to = data.contract_valid_to;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await vendors.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        

        
        

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

        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.cost_items_vendor_rel = await vendors.getCost_items_vendor_rel({
            transaction
        });
        
        
        
        
        
        
        output.company = await vendors.getCompany({
            transaction
        });
        
        
        output.logo = await vendors.getLogo({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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



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

    ];

        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.legal_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'legal_name',
                        filter.legal_name,
                    ),
                };
            }
            
            if (filter.tax_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'tax_number',
                        filter.tax_number,
                    ),
                };
            }
            
            if (filter.vat_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'vat_number',
                        filter.vat_number,
                    ),
                };
            }
            
            if (filter.iban) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'iban',
                        filter.iban,
                    ),
                };
            }
            
            if (filter.bank_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'bank_name',
                        filter.bank_name,
                    ),
                };
            }
            
            if (filter.email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'email',
                        filter.email,
                    ),
                };
            }
            
            if (filter.phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'phone',
                        filter.phone,
                    ),
                };
            }
            
            if (filter.phone2) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'phone2',
                        filter.phone2,
                    ),
                };
            }
            
            if (filter.website) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'website',
                        filter.website,
                    ),
                };
            }
            
            if (filter.address_line1) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'address_line1',
                        filter.address_line1,
                    ),
                };
            }
            
            if (filter.address_line2) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'address_line2',
                        filter.address_line2,
                    ),
                };
            }
            
            if (filter.postal_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'postal_code',
                        filter.postal_code,
                    ),
                };
            }
            
            if (filter.city) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'city',
                        filter.city,
                    ),
                };
            }
            
            if (filter.country_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'country_code',
                        filter.country_code,
                    ),
                };
            }
            
            if (filter.contact_person) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'contact_person',
                        filter.contact_person,
                    ),
                };
            }
            
            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.contract_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'contract_number',
                        filter.contract_number,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.type) {
                where = {
                    ...where,
                type: filter.type,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            


      



            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,
                        },
                    };
                }
            }
        }
        

        

        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, ) {
        let where = {};
        
        

        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,
        }));
    }

    
};

