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

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

        const store_inventory_batches = await db.store_inventory_batches.create(
            {
                id: data.id || undefined,
        
        quantity_on_hand: data.quantity_on_hand
        ||
        null
            ,
            
        received_at: data.received_at
        ||
        null
            ,
            
        expires_at: data.expires_at
        ||
        null
            ,
            
        unit_cost: data.unit_cost
        ||
        null
            ,
            
        quality_grade: data.quality_grade
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await store_inventory_batches.setStore_product( data.store_product || null, {
            transaction,
        });
        

        

        

        return store_inventory_batches;
    }
    

    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_inventory_batchesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                quantity_on_hand: item.quantity_on_hand
            ||
            null
            ,
            
                received_at: item.received_at
            ||
            null
            ,
            
                expires_at: item.expires_at
            ||
            null
            ,
            
                unit_cost: item.unit_cost
            ||
            null
            ,
            
                quality_grade: item.quality_grade
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return store_inventory_batches;
    }

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

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


        

        const updatePayload = {};
        
        if (data.quantity_on_hand !== undefined) updatePayload.quantity_on_hand = data.quantity_on_hand;
        
        
        if (data.received_at !== undefined) updatePayload.received_at = data.received_at;
        
        
        if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
        
        
        if (data.unit_cost !== undefined) updatePayload.unit_cost = data.unit_cost;
        
        
        if (data.quality_grade !== undefined) updatePayload.quality_grade = data.quality_grade;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.store_product !== undefined) {
            await store_inventory_batches.setStore_product(
              
              data.store_product,
              
              { transaction }
            );
        }
        

        
        

        

        return store_inventory_batches;
    }

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

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

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


        return store_inventory_batches;
    }

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

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

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

        await store_inventory_batches.destroy({
            transaction
        });

        return store_inventory_batches;
    }

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

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

        if (!store_inventory_batches) {
            return store_inventory_batches;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.store_product = await store_inventory_batches.getStore_product({
            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.store_products,
        as: 'store_product',
        
        where: filter.store_product ? {
          [Op.or]: [
            { id: { [Op.in]: filter.store_product.split('|').map(term => Utils.uuid(term)) } },
            {
              pricing_mode: {
                [Op.or]: filter.store_product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            received_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    expires_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

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

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

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

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

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


      



            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_inventory_batches.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_inventory_batches',
                        'quality_grade',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

