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

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

        const inventory_updates = await db.inventory_updates.create(
            {
                id: data.id || undefined,
        
        update_type: data.update_type
        ||
        null
            ,
            
        quantity_change: data.quantity_change
        ||
        null
            ,
            
        quantity_after: data.quantity_after
        ||
        null
            ,
            
        reason: data.reason
        ||
        null
            ,
            
        updated_on: data.updated_on
        ||
        null
            ,
            
        is_shortage_alert: data.is_shortage_alert
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await inventory_updates.setRural_doctor( data.rural_doctor || null, {
            transaction,
        });
        
        await inventory_updates.setMedicine( data.medicine || null, {
            transaction,
        });
        

        

        

        return inventory_updates;
    }
    

    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_updatesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                update_type: item.update_type
            ||
            null
            ,
            
                quantity_change: item.quantity_change
            ||
            null
            ,
            
                quantity_after: item.quantity_after
            ||
            null
            ,
            
                reason: item.reason
            ||
            null
            ,
            
                updated_on: item.updated_on
            ||
            null
            ,
            
                is_shortage_alert: item.is_shortage_alert
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return inventory_updates;
    }

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

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


        

        const updatePayload = {};
        
        if (data.update_type !== undefined) updatePayload.update_type = data.update_type;
        
        
        if (data.quantity_change !== undefined) updatePayload.quantity_change = data.quantity_change;
        
        
        if (data.quantity_after !== undefined) updatePayload.quantity_after = data.quantity_after;
        
        
        if (data.reason !== undefined) updatePayload.reason = data.reason;
        
        
        if (data.updated_on !== undefined) updatePayload.updated_on = data.updated_on;
        
        
        if (data.is_shortage_alert !== undefined) updatePayload.is_shortage_alert = data.is_shortage_alert;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.rural_doctor !== undefined) {
            await inventory_updates.setRural_doctor(
              
              data.rural_doctor,
              
              { transaction }
            );
        }
        
        if (data.medicine !== undefined) {
            await inventory_updates.setMedicine(
              
              data.medicine,
              
              { transaction }
            );
        }
        

        
        

        

        return inventory_updates;
    }

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

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

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


        return inventory_updates;
    }

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

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

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

        await inventory_updates.destroy({
            transaction
        });

        return inventory_updates;
    }

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

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

        if (!inventory_updates) {
            return inventory_updates;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.rural_doctor = await inventory_updates.getRural_doctor({
            transaction
        });
        
        
        output.medicine = await inventory_updates.getMedicine({
            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.rural_doctors,
        as: 'rural_doctor',
        
        where: filter.rural_doctor ? {
          [Op.or]: [
            { id: { [Op.in]: filter.rural_doctor.split('|').map(term => Utils.uuid(term)) } },
            {
              full_name: {
                [Op.or]: filter.rural_doctor.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

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

            
            

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

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

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

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

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

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

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

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

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


      

      



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

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

    
};

