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

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

        const item_supplier_links = await db.item_supplier_links.create(
            {
                id: data.id || undefined,
        
        supplier_item_code: data.supplier_item_code
        ||
        null
            ,
            
        last_purchase_price: data.last_purchase_price
        ||
        null
            ,
            
        lead_time_days: data.lead_time_days
        ||
        null
            ,
            
        min_order_qty: data.min_order_qty
        ||
        null
            ,
            
        preferred: data.preferred
        ||
        false
        
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return item_supplier_links;
    }
    

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

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

        // For each item created, replace relation files
        

        return item_supplier_links;
    }

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

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


        

        const updatePayload = {};
        
        if (data.supplier_item_code !== undefined) updatePayload.supplier_item_code = data.supplier_item_code;
        
        
        if (data.last_purchase_price !== undefined) updatePayload.last_purchase_price = data.last_purchase_price;
        
        
        if (data.lead_time_days !== undefined) updatePayload.lead_time_days = data.lead_time_days;
        
        
        if (data.min_order_qty !== undefined) updatePayload.min_order_qty = data.min_order_qty;
        
        
        if (data.preferred !== undefined) updatePayload.preferred = data.preferred;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return item_supplier_links;
    }

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

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

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


        return item_supplier_links;
    }

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

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

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

        await item_supplier_links.destroy({
            transaction
        });

        return item_supplier_links;
    }

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

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

        if (!item_supplier_links) {
            return item_supplier_links;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.item = await item_supplier_links.getItem({
            transaction
        });
        
        
        output.supplier = await item_supplier_links.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)) } },
            {
              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)) } },
            {
              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(
                        'item_supplier_links',
                        'supplier_item_code',
                        filter.supplier_item_code,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'item_supplier_links',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    last_purchase_price: {
                    ...where.last_purchase_price,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            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.min_order_qtyRange) {
                const [start, end] = filter.min_order_qtyRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    min_order_qty: {
                    ...where.min_order_qty,
                            [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.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.item_supplier_links.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(
                        'item_supplier_links',
                        'supplier_item_code',
                        query,
                    ),
                ],
            };
        }

        const records = await db.item_supplier_links.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,
        }));
    }

    
};

