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

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

        const lab_results = await db.lab_results.create(
            {
                id: data.id || undefined,
        
        result_value: data.result_value
        ||
        null
            ,
            
        unit: data.unit
        ||
        null
            ,
            
        reference_range: data.reference_range
        ||
        null
            ,
            
        remarks: data.remarks
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await lab_results.setLab_order( data.lab_order || null, {
            transaction,
        });
        
        await lab_results.setTest( data.test || null, {
            transaction,
        });
        

        

        

        return lab_results;
    }
    

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

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

        // For each item created, replace relation files
        

        return lab_results;
    }

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

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


        

        const updatePayload = {};
        
        if (data.result_value !== undefined) updatePayload.result_value = data.result_value;
        
        
        if (data.unit !== undefined) updatePayload.unit = data.unit;
        
        
        if (data.reference_range !== undefined) updatePayload.reference_range = data.reference_range;
        
        
        if (data.remarks !== undefined) updatePayload.remarks = data.remarks;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.lab_order !== undefined) {
            await lab_results.setLab_order(
              
              data.lab_order,
              
              { transaction }
            );
        }
        
        if (data.test !== undefined) {
            await lab_results.setTest(
              
              data.test,
              
              { transaction }
            );
        }
        

        
        

        

        return lab_results;
    }

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

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

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


        return lab_results;
    }

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

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

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

        await lab_results.destroy({
            transaction
        });

        return lab_results;
    }

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

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

        if (!lab_results) {
            return lab_results;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.lab_order = await lab_results.getLab_order({
            transaction
        });
        
        
        output.test = await lab_results.getTest({
            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.lab_orders,
        as: 'lab_order',
        
        where: filter.lab_order ? {
          [Op.or]: [
            { id: { [Op.in]: filter.lab_order.split('|').map(term => Utils.uuid(term)) } },
            {
              lab_order_number: {
                [Op.or]: filter.lab_order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.result_value) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'lab_results',
                        'result_value',
                        filter.result_value,
                    ),
                };
            }
            
            if (filter.unit) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'lab_results',
                        'unit',
                        filter.unit,
                    ),
                };
            }
            
            if (filter.reference_range) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'lab_results',
                        'reference_range',
                        filter.reference_range,
                    ),
                };
            }
            
            if (filter.remarks) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'lab_results',
                        'remarks',
                        filter.remarks,
                    ),
                };
            }
            

            
            

            

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

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

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

    
};

