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

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

        const medical_events = await db.medical_events.create(
            {
                id: data.id || undefined,
        
        event_at: data.event_at
        ||
        null
            ,
            
        provider_name: data.provider_name
        ||
        null
            ,
            
        facility_name: data.facility_name
        ||
        null
            ,
            
        diagnoses: data.diagnoses
        ||
        null
            ,
            
        icd10_codes: data.icd10_codes
        ||
        null
            ,
            
        procedures: data.procedures
        ||
        null
            ,
            
        medications: data.medications
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await medical_events.setReport( data.report || null, {
            transaction,
        });
        
        await medical_events.setLinked_file( data.linked_file || null, {
            transaction,
        });
        

        

        

        return medical_events;
    }
    

    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 medical_eventsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                event_at: item.event_at
            ||
            null
            ,
            
                provider_name: item.provider_name
            ||
            null
            ,
            
                facility_name: item.facility_name
            ||
            null
            ,
            
                diagnoses: item.diagnoses
            ||
            null
            ,
            
                icd10_codes: item.icd10_codes
            ||
            null
            ,
            
                procedures: item.procedures
            ||
            null
            ,
            
                medications: item.medications
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return medical_events;
    }

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

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


        

        const updatePayload = {};
        
        if (data.event_at !== undefined) updatePayload.event_at = data.event_at;
        
        
        if (data.provider_name !== undefined) updatePayload.provider_name = data.provider_name;
        
        
        if (data.facility_name !== undefined) updatePayload.facility_name = data.facility_name;
        
        
        if (data.diagnoses !== undefined) updatePayload.diagnoses = data.diagnoses;
        
        
        if (data.icd10_codes !== undefined) updatePayload.icd10_codes = data.icd10_codes;
        
        
        if (data.procedures !== undefined) updatePayload.procedures = data.procedures;
        
        
        if (data.medications !== undefined) updatePayload.medications = data.medications;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.report !== undefined) {
            await medical_events.setReport(
              
              data.report,
              
              { transaction }
            );
        }
        
        if (data.linked_file !== undefined) {
            await medical_events.setLinked_file(
              
              data.linked_file,
              
              { transaction }
            );
        }
        

        
        

        

        return medical_events;
    }

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

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

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


        return medical_events;
    }

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

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

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

        await medical_events.destroy({
            transaction
        });

        return medical_events;
    }

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

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

        if (!medical_events) {
            return medical_events;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.report = await medical_events.getReport({
            transaction
        });
        
        
        output.linked_file = await medical_events.getLinked_file({
            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.medical_chronology_reports,
        as: 'report',
        
        where: filter.report ? {
          [Op.or]: [
            { id: { [Op.in]: filter.report.split('|').map(term => Utils.uuid(term)) } },
            {
              report_title: {
                [Op.or]: filter.report.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.provider_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medical_events',
                        'provider_name',
                        filter.provider_name,
                    ),
                };
            }
            
            if (filter.facility_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medical_events',
                        'facility_name',
                        filter.facility_name,
                    ),
                };
            }
            
            if (filter.diagnoses) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medical_events',
                        'diagnoses',
                        filter.diagnoses,
                    ),
                };
            }
            
            if (filter.icd10_codes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medical_events',
                        'icd10_codes',
                        filter.icd10_codes,
                    ),
                };
            }
            
            if (filter.procedures) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medical_events',
                        'procedures',
                        filter.procedures,
                    ),
                };
            }
            
            if (filter.medications) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medical_events',
                        'medications',
                        filter.medications,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medical_events',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            event_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    event_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

    
};

