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

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

        const ecg_stress_tests = await db.ecg_stress_tests.create(
            {
                id: data.id || undefined,
        
        test_number: data.test_number
        ||
        null
            ,
            
        result_text: data.result_text
        ||
        null
            ,
            
        price: data.price
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await ecg_stress_tests.setPatient( data.patient || null, {
            transaction,
        });
        
        await ecg_stress_tests.setDoctor( data.doctor || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.ecg_stress_tests.getTableName(),
                belongsToColumn: 'result_files',
                belongsToId: ecg_stress_tests.id,
            },
            data.result_files,
            options,
        );
        

        return ecg_stress_tests;
    }
    

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

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

        // For each item created, replace relation files
        
        for (let i = 0; i < ecg_stress_tests.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.ecg_stress_tests.getTableName(),
                    belongsToColumn: 'result_files',
                    belongsToId: ecg_stress_tests[i].id,
                },
                data[i].result_files,
                options,
            );
        }
        

        return ecg_stress_tests;
    }

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

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


        

        const updatePayload = {};
        
        if (data.test_number !== undefined) updatePayload.test_number = data.test_number;
        
        
        if (data.result_text !== undefined) updatePayload.result_text = data.result_text;
        
        
        if (data.price !== undefined) updatePayload.price = data.price;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.patient !== undefined) {
            await ecg_stress_tests.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.doctor !== undefined) {
            await ecg_stress_tests.setDoctor(
              
              data.doctor,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.ecg_stress_tests.getTableName(),
                belongsToColumn: 'result_files',
                belongsToId: ecg_stress_tests.id,
            },
            data.result_files,
            options,
        );
        

        return ecg_stress_tests;
    }

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

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

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


        return ecg_stress_tests;
    }

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

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

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

        await ecg_stress_tests.destroy({
            transaction
        });

        return ecg_stress_tests;
    }

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

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

        if (!ecg_stress_tests) {
            return ecg_stress_tests;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.patient = await ecg_stress_tests.getPatient({
            transaction
        });
        
        
        output.doctor = await ecg_stress_tests.getDoctor({
            transaction
        });
        
        
        output.result_files = await ecg_stress_tests.getResult_files({
            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.patients,
        as: 'patient',
        
        where: filter.patient ? {
          [Op.or]: [
            { id: { [Op.in]: filter.patient.split('|').map(term => Utils.uuid(term)) } },
            {
              full_name: {
                [Op.or]: filter.patient.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



      {
        model: db.file,
        as: 'result_files',
      },

    ];

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

            
            if (filter.test_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ecg_stress_tests',
                        'test_number',
                        filter.test_number,
                    ),
                };
            }
            
            if (filter.result_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ecg_stress_tests',
                        'result_text',
                        filter.result_text,
                    ),
                };
            }
            

            
            

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

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

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

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

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

    
};

