
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
            ,
            
        category: data.category
        ||
        null
            ,
            
        strength: data.strength
        ||
        null
            ,
            
        unit: data.unit
        ||
        null
            ,
            
        manufacturer: data.manufacturer
        ||
        null
            ,
            
        unit_price: data.unit_price
        ||
        null
            ,
            
        requires_prescription: data.requires_prescription
        ||
        false
        
            ,
            
        reorder_level: data.reorder_level
        ||
        null
            ,
            
        storage_instructions: data.storage_instructions
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { 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
            ,
            
                category: item.category
            ||
            null
            ,
            
                strength: item.strength
            ||
            null
            ,
            
                unit: item.unit
            ||
            null
            ,
            
                manufacturer: item.manufacturer
            ||
            null
            ,
            
                unit_price: item.unit_price
            ||
            null
            ,
            
                requires_prescription: item.requires_prescription
            ||
            false
        
            ,
            
                reorder_level: item.reorder_level
            ||
            null
            ,
            
                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 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.category !== undefined) updatePayload.category = data.category;
        
        
        if (data.strength !== undefined) updatePayload.strength = data.strength;
        
        
        if (data.unit !== undefined) updatePayload.unit = data.unit;
        
        
        if (data.manufacturer !== undefined) updatePayload.manufacturer = data.manufacturer;
        
        
        if (data.unit_price !== undefined) updatePayload.unit_price = data.unit_price;
        
        
        if (data.requires_prescription !== undefined) updatePayload.requires_prescription = data.requires_prescription;
        
        
        if (data.reorder_level !== undefined) updatePayload.reorder_level = data.reorder_level;
        
        
        if (data.storage_instructions !== undefined) updatePayload.storage_instructions = data.storage_instructions;
        
        
        updatePayload.updatedById = currentUser.id;

        await medicines.update(updatePayload, {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_updates_medicine = await medicines.getInventory_updates_medicine({
            transaction
        });
        
        
        
        output.dispatch_items_medicine = await medicines.getDispatch_items_medicine({
            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 = [



    ];

        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.unit) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medicines',
                        'unit',
                        filter.unit,
                    ),
                };
            }
            
            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.unit_priceRange) {
                const [start, end] = filter.unit_priceRange;

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

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

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

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

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

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




            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.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, ) {
        let where = {};
        
        

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

    
};

