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

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

        const pharmacy_inventory = await db.pharmacy_inventory.create(
            {
                id: data.id || undefined,
        
        drug_name: data.drug_name
        ||
        null
            ,
            
        supplier: data.supplier
        ||
        null
            ,
            
        wholesale_price: data.wholesale_price
        ||
        null
            ,
            
        retail_price: data.retail_price
        ||
        null
            ,
            
        quantity: data.quantity
        ||
        null
            ,
            
        expiry_date: data.expiry_date
        ||
        null
            ,
            
        batch_number: data.batch_number
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return pharmacy_inventory;
    }
    

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

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

        // For each item created, replace relation files
        

        return pharmacy_inventory;
    }

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

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


        

        const updatePayload = {};
        
        if (data.drug_name !== undefined) updatePayload.drug_name = data.drug_name;
        
        
        if (data.supplier !== undefined) updatePayload.supplier = data.supplier;
        
        
        if (data.wholesale_price !== undefined) updatePayload.wholesale_price = data.wholesale_price;
        
        
        if (data.retail_price !== undefined) updatePayload.retail_price = data.retail_price;
        
        
        if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
        
        
        if (data.expiry_date !== undefined) updatePayload.expiry_date = data.expiry_date;
        
        
        if (data.batch_number !== undefined) updatePayload.batch_number = data.batch_number;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return pharmacy_inventory;
    }

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

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

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


        return pharmacy_inventory;
    }

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

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

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

        await pharmacy_inventory.destroy({
            transaction
        });

        return pharmacy_inventory;
    }

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

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

        if (!pharmacy_inventory) {
            return pharmacy_inventory;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        

        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.drug_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'pharmacy_inventory',
                        'drug_name',
                        filter.drug_name,
                    ),
                };
            }
            
            if (filter.supplier) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'pharmacy_inventory',
                        'supplier',
                        filter.supplier,
                    ),
                };
            }
            
            if (filter.batch_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'pharmacy_inventory',
                        'batch_number',
                        filter.batch_number,
                    ),
                };
            }
            

            
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    retail_price: {
                    ...where.retail_price,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            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.expiry_dateRange) {
                const [start, end] = filter.expiry_dateRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    expiry_date: {
                    ...where.expiry_date,
                            [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.pharmacy_inventory.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(
                        'pharmacy_inventory',
                        'drug_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

