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

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

        const store_products = await db.store_products.create(
            {
                id: data.id || undefined,
        
        current_price: data.current_price
        ||
        null
            ,
            
        pricing_mode: data.pricing_mode
        ||
        null
            ,
            
        reorder_point: data.reorder_point
        ||
        null
            ,
            
        target_stock: data.target_stock
        ||
        null
            ,
            
        is_listed: data.is_listed
        ||
        false
        
            ,
            
        tax_rate: data.tax_rate
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await store_products.setStore( data.store || null, {
            transaction,
        });
        
        await store_products.setItem( data.item || null, {
            transaction,
        });
        

        

        

        return store_products;
    }
    

    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 store_productsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                current_price: item.current_price
            ||
            null
            ,
            
                pricing_mode: item.pricing_mode
            ||
            null
            ,
            
                reorder_point: item.reorder_point
            ||
            null
            ,
            
                target_stock: item.target_stock
            ||
            null
            ,
            
                is_listed: item.is_listed
            ||
            false
        
            ,
            
                tax_rate: item.tax_rate
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return store_products;
    }

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

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


        

        const updatePayload = {};
        
        if (data.current_price !== undefined) updatePayload.current_price = data.current_price;
        
        
        if (data.pricing_mode !== undefined) updatePayload.pricing_mode = data.pricing_mode;
        
        
        if (data.reorder_point !== undefined) updatePayload.reorder_point = data.reorder_point;
        
        
        if (data.target_stock !== undefined) updatePayload.target_stock = data.target_stock;
        
        
        if (data.is_listed !== undefined) updatePayload.is_listed = data.is_listed;
        
        
        if (data.tax_rate !== undefined) updatePayload.tax_rate = data.tax_rate;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.store !== undefined) {
            await store_products.setStore(
              
              data.store,
              
              { transaction }
            );
        }
        
        if (data.item !== undefined) {
            await store_products.setItem(
              
              data.item,
              
              { transaction }
            );
        }
        

        
        

        

        return store_products;
    }

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

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

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


        return store_products;
    }

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

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

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

        await store_products.destroy({
            transaction
        });

        return store_products;
    }

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

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

        if (!store_products) {
            return store_products;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.store_inventory_batches_store_product = await store_products.getStore_inventory_batches_store_product({
            transaction
        });
        
        
        
        
        
        
        output.shelf_slots_store_product = await store_products.getShelf_slots_store_product({
            transaction
        });
        
        
        
        
        output.sales_transaction_lines_store_product = await store_products.getSales_transaction_lines_store_product({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.store = await store_products.getStore({
            transaction
        });
        
        
        output.item = await store_products.getItem({
            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.market_stores,
        as: 'store',
        
        where: filter.store ? {
          [Op.or]: [
            { id: { [Op.in]: filter.store.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.store.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            

            
            

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

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

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

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

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

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

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

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

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

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

            
            if (filter.pricing_mode) {
                where = {
                    ...where,
                pricing_mode: filter.pricing_mode,
            };
            }
            
            if (filter.is_listed) {
                where = {
                    ...where,
                is_listed: filter.is_listed,
            };
            }
            


      

      



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

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

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

    
};

