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

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

        const approved_vendors = await db.approved_vendors.create(
            {
                id: data.id || undefined,
        
        supplier_item_code: data.supplier_item_code
        ||
        null
            ,
            
        lead_time_days: data.lead_time_days
        ||
        null
            ,
            
        last_price: data.last_price
        ||
        null
            ,
            
        preferred: data.preferred
        ||
        false
        
            ,
            
        active: data.active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await approved_vendors.setItem( data.item || null, {
            transaction,
        });
        
        await approved_vendors.setSupplier( data.supplier || null, {
            transaction,
        });
        

        

        

        return approved_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 approved_vendorsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                supplier_item_code: item.supplier_item_code
            ||
            null
            ,
            
                lead_time_days: item.lead_time_days
            ||
            null
            ,
            
                last_price: item.last_price
            ||
            null
            ,
            
                preferred: item.preferred
            ||
            false
        
            ,
            
                active: item.active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return approved_vendors;
    }

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

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


        

        const updatePayload = {};
        
        if (data.supplier_item_code !== undefined) updatePayload.supplier_item_code = data.supplier_item_code;
        
        
        if (data.lead_time_days !== undefined) updatePayload.lead_time_days = data.lead_time_days;
        
        
        if (data.last_price !== undefined) updatePayload.last_price = data.last_price;
        
        
        if (data.preferred !== undefined) updatePayload.preferred = data.preferred;
        
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.item !== undefined) {
            await approved_vendors.setItem(
              
              data.item,
              
              { transaction }
            );
        }
        
        if (data.supplier !== undefined) {
            await approved_vendors.setSupplier(
              
              data.supplier,
              
              { transaction }
            );
        }
        

        
        

        

        return approved_vendors;
    }

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

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

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


        return approved_vendors;
    }

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

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

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

        await approved_vendors.destroy({
            transaction
        });

        return approved_vendors;
    }

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

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

        if (!approved_vendors) {
            return approved_vendors;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.item = await approved_vendors.getItem({
            transaction
        });
        
        
        output.supplier = await approved_vendors.getSupplier({
            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.items,
        as: 'item',
        
        where: filter.item ? {
          [Op.or]: [
            { id: { [Op.in]: filter.item.split('|').map(term => Utils.uuid(term)) } },
            {
              item_name: {
                [Op.or]: filter.item.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)) } },
            {
              supplier_name: {
                [Op.or]: filter.supplier.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.supplier_item_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'approved_vendors',
                        'supplier_item_code',
                        filter.supplier_item_code,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.preferred) {
                where = {
                    ...where,
                preferred: filter.preferred,
            };
            }
            
            if (filter.active) {
                where = {
                    ...where,
                active: filter.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.approved_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(
                        'approved_vendors',
                        'supplier_item_code',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

