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

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

        const patients = await db.patients.create(
            {
                id: data.id || undefined,
        
        patient_code: data.patient_code
        ||
        null
            ,
            
        first_name: data.first_name
        ||
        null
            ,
            
        last_name: data.last_name
        ||
        null
            ,
            
        date_of_birth: data.date_of_birth
        ||
        null
            ,
            
        sex: data.sex
        ||
        null
            ,
            
        disease_stage: data.disease_stage
        ||
        null
            ,
            
        diagnosis_date: data.diagnosis_date
        ||
        null
            ,
            
        medical_notes: data.medical_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await patients.setAccount( data.account || null, {
            transaction,
        });
        
        await patients.setPrimary_physician( data.primary_physician || null, {
            transaction,
        });
        

        

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

        return patients;
    }
    

    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 patientsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                patient_code: item.patient_code
            ||
            null
            ,
            
                first_name: item.first_name
            ||
            null
            ,
            
                last_name: item.last_name
            ||
            null
            ,
            
                date_of_birth: item.date_of_birth
            ||
            null
            ,
            
                sex: item.sex
            ||
            null
            ,
            
                disease_stage: item.disease_stage
            ||
            null
            ,
            
                diagnosis_date: item.diagnosis_date
            ||
            null
            ,
            
                medical_notes: item.medical_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return patients;
    }

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

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


        

        const updatePayload = {};
        
        if (data.patient_code !== undefined) updatePayload.patient_code = data.patient_code;
        
        
        if (data.first_name !== undefined) updatePayload.first_name = data.first_name;
        
        
        if (data.last_name !== undefined) updatePayload.last_name = data.last_name;
        
        
        if (data.date_of_birth !== undefined) updatePayload.date_of_birth = data.date_of_birth;
        
        
        if (data.sex !== undefined) updatePayload.sex = data.sex;
        
        
        if (data.disease_stage !== undefined) updatePayload.disease_stage = data.disease_stage;
        
        
        if (data.diagnosis_date !== undefined) updatePayload.diagnosis_date = data.diagnosis_date;
        
        
        if (data.medical_notes !== undefined) updatePayload.medical_notes = data.medical_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.account !== undefined) {
            await patients.setAccount(
              
              data.account,
              
              { transaction }
            );
        }
        
        if (data.primary_physician !== undefined) {
            await patients.setPrimary_physician(
              
              data.primary_physician,
              
              { transaction }
            );
        }
        

        
        

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

        return patients;
    }

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

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

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


        return patients;
    }

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

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

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

        await patients.destroy({
            transaction
        });

        return patients;
    }

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

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

        if (!patients) {
            return patients;
        }

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

        
        
        
        
        
        
        output.patient_access_grants_patient = await patients.getPatient_access_grants_patient({
            transaction
        });
        
        
        output.medications_patient = await patients.getMedications_patient({
            transaction
        });
        
        
        output.medication_schedules_patient = await patients.getMedication_schedules_patient({
            transaction
        });
        
        
        output.calendar_events_patient = await patients.getCalendar_events_patient({
            transaction
        });
        
        
        output.reminders_patient = await patients.getReminders_patient({
            transaction
        });
        
        
        
        
        output.cognitive_sessions_patient = await patients.getCognitive_sessions_patient({
            transaction
        });
        
        
        
        output.stage_assessments_patient = await patients.getStage_assessments_patient({
            transaction
        });
        
        
        output.voice_assistant_sessions_patient = await patients.getVoice_assistant_sessions_patient({
            transaction
        });
        
        
        output.iot_devices_patient = await patients.getIot_devices_patient({
            transaction
        });
        
        
        output.iot_telemetry_events_patient = await patients.getIot_telemetry_events_patient({
            transaction
        });
        
        
        output.geofences_patient = await patients.getGeofences_patient({
            transaction
        });
        
        
        output.alerts_patient = await patients.getAlerts_patient({
            transaction
        });
        
        
        
        output.shared_dashboard_posts_patient = await patients.getShared_dashboard_posts_patient({
            transaction
        });
        
        
        
        output.article_recommendations_patient = await patients.getArticle_recommendations_patient({
            transaction
        });
        
        
        output.clinical_reports_patient = await patients.getClinical_reports_patient({
            transaction
        });
        
        
        
        
        output.profile_photo = await patients.getProfile_photo({
            transaction
        });
        
        
        output.account = await patients.getAccount({
            transaction
        });
        
        
        output.primary_physician = await patients.getPrimary_physician({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userAccounts = (user && user.accounts?.id) || null;
        

        
        if (userAccounts) {
            if (options?.currentUser?.accountsId) {
                where.accountsId = options.currentUser.accountsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.accounts,
        as: 'account',
        
      },

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



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

    ];

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

            
            if (filter.patient_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'patients',
                        'patient_code',
                        filter.patient_code,
                    ),
                };
            }
            
            if (filter.first_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'patients',
                        'first_name',
                        filter.first_name,
                    ),
                };
            }
            
            if (filter.last_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'patients',
                        'last_name',
                        filter.last_name,
                    ),
                };
            }
            
            if (filter.medical_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'patients',
                        'medical_notes',
                        filter.medical_notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.sex) {
                where = {
                    ...where,
                sex: filter.sex,
            };
            }
            
            if (filter.disease_stage) {
                where = {
                    ...where,
                disease_stage: filter.disease_stage,
            };
            }
            


      
      if (filter.account) {
        const listItems = filter.account.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          accountId: {[Op.or]: listItems}
        };
      }
      

      



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

        
        if (globalAccess) {
            delete where.accountsId;
        }
        

        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.patients.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'patients',
                        'last_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

