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

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

        const medicines = await db.medicines.create(
            {
                id: data.id || undefined,
        
        medicine_name: data.medicine_name
        ||
        null
            ,
            
        generic_name: data.generic_name
        ||
        null
            ,
            
        strength: data.strength
        ||
        null
            ,
            
        dosage_form: data.dosage_form
        ||
        null
            ,
            
        manufacturer: data.manufacturer
        ||
        null
            ,
            
        requires_prescription: data.requires_prescription
        ||
        false
        
            ,
            
        storage_instructions: data.storage_instructions
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await medicines.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return medicines;
    }
    

    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 medicinesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                medicine_name: item.medicine_name
            ||
            null
            ,
            
                generic_name: item.generic_name
            ||
            null
            ,
            
                strength: item.strength
            ||
            null
            ,
            
                dosage_form: item.dosage_form
            ||
            null
            ,
            
                manufacturer: item.manufacturer
            ||
            null
            ,
            
                requires_prescription: item.requires_prescription
            ||
            false
        
            ,
            
                storage_instructions: item.storage_instructions
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return medicines;
    }

    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 medicines = await db.medicines.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.medicine_name !== undefined) updatePayload.medicine_name = data.medicine_name;
        
        
        if (data.generic_name !== undefined) updatePayload.generic_name = data.generic_name;
        
        
        if (data.strength !== undefined) updatePayload.strength = data.strength;
        
        
        if (data.dosage_form !== undefined) updatePayload.dosage_form = data.dosage_form;
        
        
        if (data.manufacturer !== undefined) updatePayload.manufacturer = data.manufacturer;
        
        
        if (data.requires_prescription !== undefined) updatePayload.requires_prescription = data.requires_prescription;
        
        
        if (data.storage_instructions !== undefined) updatePayload.storage_instructions = data.storage_instructions;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organizations !== undefined) {
            await medicines.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return medicines;
    }

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

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

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


        return medicines;
    }

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

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

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

        await medicines.destroy({
            transaction
        });

        return medicines;
    }

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

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

        if (!medicines) {
            return medicines;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        output.inventory_items_medicine = await medicines.getInventory_items_medicine({
            transaction
        });
        
        
        
        output.prescription_items_medicine = await medicines.getPrescription_items_medicine({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        output.organizations = await medicines.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.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.medicine_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medicines',
                        'medicine_name',
                        filter.medicine_name,
                    ),
                };
            }
            
            if (filter.generic_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medicines',
                        'generic_name',
                        filter.generic_name,
                    ),
                };
            }
            
            if (filter.strength) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medicines',
                        'strength',
                        filter.strength,
                    ),
                };
            }
            
            if (filter.manufacturer) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medicines',
                        'manufacturer',
                        filter.manufacturer,
                    ),
                };
            }
            
            if (filter.storage_instructions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medicines',
                        'storage_instructions',
                        filter.storage_instructions,
                    ),
                };
            }
            

            
            

            

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

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


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

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

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

    
};

