
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,
        
        vendorCode: data.vendorCode
        ||
        null
            ,
            
        vendorName: data.vendorName
        ||
        null
            ,
            
        vendorType: data.vendorType
        ||
        null
            ,
            
        taxClassification: data.taxClassification
        ||
        null
            ,
            
        tinNumber: data.tinNumber
        ||
        null
            ,
            
        birRegAddress: data.birRegAddress
        ||
        null
            ,
            
        contactPerson: data.contactPerson
        ||
        null
            ,
            
        contactNumber: data.contactNumber
        ||
        null
            ,
            
        email: data.email
        ||
        null
            ,
            
        address: data.address
        ||
        null
            ,
            
        paymentTermsDays: data.paymentTermsDays
        ||
        null
            ,
            
        wtaxAtcCode: data.wtaxAtcCode
        ||
        null
            ,
            
        wtaxRate: data.wtaxRate
        ||
        null
            ,
            
        bankName: data.bankName
        ||
        null
            ,
            
        bankAccountNumber: data.bankAccountNumber
        ||
        null
            ,
            
        bankAccountName: data.bankAccountName
        ||
        null
            ,
            
        isActive: data.isActive
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await vendors.setDefaultAccount( data.defaultAccount || 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,
                
                vendorCode: item.vendorCode
            ||
            null
            ,
            
                vendorName: item.vendorName
            ||
            null
            ,
            
                vendorType: item.vendorType
            ||
            null
            ,
            
                taxClassification: item.taxClassification
            ||
            null
            ,
            
                tinNumber: item.tinNumber
            ||
            null
            ,
            
                birRegAddress: item.birRegAddress
            ||
            null
            ,
            
                contactPerson: item.contactPerson
            ||
            null
            ,
            
                contactNumber: item.contactNumber
            ||
            null
            ,
            
                email: item.email
            ||
            null
            ,
            
                address: item.address
            ||
            null
            ,
            
                paymentTermsDays: item.paymentTermsDays
            ||
            null
            ,
            
                wtaxAtcCode: item.wtaxAtcCode
            ||
            null
            ,
            
                wtaxRate: item.wtaxRate
            ||
            null
            ,
            
                bankName: item.bankName
            ||
            null
            ,
            
                bankAccountNumber: item.bankAccountNumber
            ||
            null
            ,
            
                bankAccountName: item.bankAccountName
            ||
            null
            ,
            
                isActive: item.isActive
            ||
            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
        

        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.vendorCode !== undefined) updatePayload.vendorCode = data.vendorCode;
        
        
        if (data.vendorName !== undefined) updatePayload.vendorName = data.vendorName;
        
        
        if (data.vendorType !== undefined) updatePayload.vendorType = data.vendorType;
        
        
        if (data.taxClassification !== undefined) updatePayload.taxClassification = data.taxClassification;
        
        
        if (data.tinNumber !== undefined) updatePayload.tinNumber = data.tinNumber;
        
        
        if (data.birRegAddress !== undefined) updatePayload.birRegAddress = data.birRegAddress;
        
        
        if (data.contactPerson !== undefined) updatePayload.contactPerson = data.contactPerson;
        
        
        if (data.contactNumber !== undefined) updatePayload.contactNumber = data.contactNumber;
        
        
        if (data.email !== undefined) updatePayload.email = data.email;
        
        
        if (data.address !== undefined) updatePayload.address = data.address;
        
        
        if (data.paymentTermsDays !== undefined) updatePayload.paymentTermsDays = data.paymentTermsDays;
        
        
        if (data.wtaxAtcCode !== undefined) updatePayload.wtaxAtcCode = data.wtaxAtcCode;
        
        
        if (data.wtaxRate !== undefined) updatePayload.wtaxRate = data.wtaxRate;
        
        
        if (data.bankName !== undefined) updatePayload.bankName = data.bankName;
        
        
        if (data.bankAccountNumber !== undefined) updatePayload.bankAccountNumber = data.bankAccountNumber;
        
        
        if (data.bankAccountName !== undefined) updatePayload.bankAccountName = data.bankAccountName;
        
        
        if (data.isActive !== undefined) updatePayload.isActive = data.isActive;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.defaultAccount !== undefined) {
            await vendors.setDefaultAccount(
              
              data.defaultAccount,
              
              { 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.ap_invoices_vendor = await vendors.getAp_invoices_vendor({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.defaultAccount = await vendors.getDefaultAccount({
            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.accounts,
        as: 'defaultAccount',
        
        where: filter.defaultAccount ? {
          [Op.or]: [
            { id: { [Op.in]: filter.defaultAccount.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.defaultAccount.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.vendorCode) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'vendorCode',
                        filter.vendorCode,
                    ),
                };
            }
            
            if (filter.vendorName) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'vendorName',
                        filter.vendorName,
                    ),
                };
            }
            
            if (filter.tinNumber) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'tinNumber',
                        filter.tinNumber,
                    ),
                };
            }
            
            if (filter.birRegAddress) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'birRegAddress',
                        filter.birRegAddress,
                    ),
                };
            }
            
            if (filter.contactPerson) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'contactPerson',
                        filter.contactPerson,
                    ),
                };
            }
            
            if (filter.contactNumber) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'contactNumber',
                        filter.contactNumber,
                    ),
                };
            }
            
            if (filter.email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'email',
                        filter.email,
                    ),
                };
            }
            
            if (filter.address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'address',
                        filter.address,
                    ),
                };
            }
            
            if (filter.wtaxAtcCode) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'wtaxAtcCode',
                        filter.wtaxAtcCode,
                    ),
                };
            }
            
            if (filter.bankName) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'bankName',
                        filter.bankName,
                    ),
                };
            }
            
            if (filter.bankAccountNumber) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'bankAccountNumber',
                        filter.bankAccountNumber,
                    ),
                };
            }
            
            if (filter.bankAccountName) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vendors',
                        'bankAccountName',
                        filter.bankAccountName,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.vendorType) {
                where = {
                    ...where,
                vendorType: filter.vendorType,
            };
            }
            
            if (filter.taxClassification) {
                where = {
                    ...where,
                taxClassification: filter.taxClassification,
            };
            }
            
            if (filter.isActive) {
                where = {
                    ...where,
                isActive: filter.isActive,
            };
            }
            


      



            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',
                        'vendorName',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

