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

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

        const inventory_adjustments = await db.inventory_adjustments.create(
            {
                id: data.id || undefined,
        
        adjustment_type: data.adjustment_type
        ||
        null
            ,
            
        delta_quantity: data.delta_quantity
        ||
        null
            ,
            
        resulting_quantity: data.resulting_quantity
        ||
        null
            ,
            
        reason: data.reason
        ||
        null
            ,
            
        adjusted_at: data.adjusted_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await inventory_adjustments.setVariant( data.variant || null, {
            transaction,
        });
        
        await inventory_adjustments.setAdjusted_by_user( data.adjusted_by_user || null, {
            transaction,
        });
        
        await inventory_adjustments.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return inventory_adjustments;
    }
    

    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 inventory_adjustmentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                adjustment_type: item.adjustment_type
            ||
            null
            ,
            
                delta_quantity: item.delta_quantity
            ||
            null
            ,
            
                resulting_quantity: item.resulting_quantity
            ||
            null
            ,
            
                reason: item.reason
            ||
            null
            ,
            
                adjusted_at: item.adjusted_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return inventory_adjustments;
    }

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

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


        

        const updatePayload = {};
        
        if (data.adjustment_type !== undefined) updatePayload.adjustment_type = data.adjustment_type;
        
        
        if (data.delta_quantity !== undefined) updatePayload.delta_quantity = data.delta_quantity;
        
        
        if (data.resulting_quantity !== undefined) updatePayload.resulting_quantity = data.resulting_quantity;
        
        
        if (data.reason !== undefined) updatePayload.reason = data.reason;
        
        
        if (data.adjusted_at !== undefined) updatePayload.adjusted_at = data.adjusted_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.variant !== undefined) {
            await inventory_adjustments.setVariant(
              
              data.variant,
              
              { transaction }
            );
        }
        
        if (data.adjusted_by_user !== undefined) {
            await inventory_adjustments.setAdjusted_by_user(
              
              data.adjusted_by_user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await inventory_adjustments.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return inventory_adjustments;
    }

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

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

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


        return inventory_adjustments;
    }

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

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

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

        await inventory_adjustments.destroy({
            transaction
        });

        return inventory_adjustments;
    }

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

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

        if (!inventory_adjustments) {
            return inventory_adjustments;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.variant = await inventory_adjustments.getVariant({
            transaction
        });
        
        
        output.adjusted_by_user = await inventory_adjustments.getAdjusted_by_user({
            transaction
        });
        
        
        output.organizations = await inventory_adjustments.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.product_variants,
        as: 'variant',
        
        where: filter.variant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.variant.split('|').map(term => Utils.uuid(term)) } },
            {
              variant_title: {
                [Op.or]: filter.variant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.users,
        as: 'adjusted_by_user',
        
        where: filter.adjusted_by_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.adjusted_by_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.adjusted_by_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

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

            
            

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

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

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

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

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

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

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

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

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


      

      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.inventory_adjustments.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'inventory_adjustments',
                        'reason',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

