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

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

        const dispatch_items = await db.dispatch_items.create(
            {
                id: data.id || undefined,
        
        quantity: data.quantity
        ||
        null
            ,
            
        dosage_instructions: data.dosage_instructions
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await dispatch_items.setMedicine_dispatch( data.medicine_dispatch || null, {
            transaction,
        });
        
        await dispatch_items.setMedicine( data.medicine || null, {
            transaction,
        });
        

        

        

        return dispatch_items;
    }
    

    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 dispatch_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                quantity: item.quantity
            ||
            null
            ,
            
                dosage_instructions: item.dosage_instructions
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return dispatch_items;
    }

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

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


        

        const updatePayload = {};
        
        if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
        
        
        if (data.dosage_instructions !== undefined) updatePayload.dosage_instructions = data.dosage_instructions;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.medicine_dispatch !== undefined) {
            await dispatch_items.setMedicine_dispatch(
              
              data.medicine_dispatch,
              
              { transaction }
            );
        }
        
        if (data.medicine !== undefined) {
            await dispatch_items.setMedicine(
              
              data.medicine,
              
              { transaction }
            );
        }
        

        
        

        

        return dispatch_items;
    }

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

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

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


        return dispatch_items;
    }

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

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

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

        await dispatch_items.destroy({
            transaction
        });

        return dispatch_items;
    }

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

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

        if (!dispatch_items) {
            return dispatch_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.medicine_dispatch = await dispatch_items.getMedicine_dispatch({
            transaction
        });
        
        
        output.medicine = await dispatch_items.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.medicine_dispatches,
        as: 'medicine_dispatch',
        
        where: filter.medicine_dispatch ? {
          [Op.or]: [
            { id: { [Op.in]: filter.medicine_dispatch.split('|').map(term => Utils.uuid(term)) } },
            {
              tracking_reference: {
                [Op.or]: filter.medicine_dispatch.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.dosage_instructions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'dispatch_items',
                        'dosage_instructions',
                        filter.dosage_instructions,
                    ),
                };
            }
            

            
            

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

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

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

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

            


      

      



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

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

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

    
};

