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

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

        const patient_profiles = await db.patient_profiles.create(
            {
                id: data.id || undefined,
        
        patient_identifier: data.patient_identifier
        ||
        null
            ,
            
        gender: data.gender
        ||
        null
            ,
            
        date_of_birth: data.date_of_birth
        ||
        null
            ,
            
        blood_group: data.blood_group
        ||
        null
            ,
            
        address_line: data.address_line
        ||
        null
            ,
            
        village: data.village
        ||
        null
            ,
            
        district: data.district
        ||
        null
            ,
            
        state: data.state
        ||
        null
            ,
            
        consent_for_telemedicine: data.consent_for_telemedicine
        ||
        false
        
            ,
            
        consent_for_notifications: data.consent_for_notifications
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await patient_profiles.setUser( data.user || null, {
            transaction,
        });
        
        await patient_profiles.setRegistered_at_camp( data.registered_at_camp || null, {
            transaction,
        });
        
        await patient_profiles.setPrimary_rural_doctor( data.primary_rural_doctor || null, {
            transaction,
        });
        
        await patient_profiles.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return patient_profiles;
    }
    

    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 patient_profilesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                patient_identifier: item.patient_identifier
            ||
            null
            ,
            
                gender: item.gender
            ||
            null
            ,
            
                date_of_birth: item.date_of_birth
            ||
            null
            ,
            
                blood_group: item.blood_group
            ||
            null
            ,
            
                address_line: item.address_line
            ||
            null
            ,
            
                village: item.village
            ||
            null
            ,
            
                district: item.district
            ||
            null
            ,
            
                state: item.state
            ||
            null
            ,
            
                consent_for_telemedicine: item.consent_for_telemedicine
            ||
            false
        
            ,
            
                consent_for_notifications: item.consent_for_notifications
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return patient_profiles;
    }

    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 patient_profiles = await db.patient_profiles.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.patient_identifier !== undefined) updatePayload.patient_identifier = data.patient_identifier;
        
        
        if (data.gender !== undefined) updatePayload.gender = data.gender;
        
        
        if (data.date_of_birth !== undefined) updatePayload.date_of_birth = data.date_of_birth;
        
        
        if (data.blood_group !== undefined) updatePayload.blood_group = data.blood_group;
        
        
        if (data.address_line !== undefined) updatePayload.address_line = data.address_line;
        
        
        if (data.village !== undefined) updatePayload.village = data.village;
        
        
        if (data.district !== undefined) updatePayload.district = data.district;
        
        
        if (data.state !== undefined) updatePayload.state = data.state;
        
        
        if (data.consent_for_telemedicine !== undefined) updatePayload.consent_for_telemedicine = data.consent_for_telemedicine;
        
        
        if (data.consent_for_notifications !== undefined) updatePayload.consent_for_notifications = data.consent_for_notifications;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await patient_profiles.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.registered_at_camp !== undefined) {
            await patient_profiles.setRegistered_at_camp(
              
              data.registered_at_camp,
              
              { transaction }
            );
        }
        
        if (data.primary_rural_doctor !== undefined) {
            await patient_profiles.setPrimary_rural_doctor(
              
              data.primary_rural_doctor,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await patient_profiles.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return patient_profiles;
    }

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

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

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


        return patient_profiles;
    }

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

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

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

        await patient_profiles.destroy({
            transaction
        });

        return patient_profiles;
    }

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

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

        if (!patient_profiles) {
            return patient_profiles;
        }

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

        
        
        
        
        
        
        
        
        output.appointments_patient = await patient_profiles.getAppointments_patient({
            transaction
        });
        
        
        output.consultations_patient = await patient_profiles.getConsultations_patient({
            transaction
        });
        
        
        output.medical_reports_patient = await patient_profiles.getMedical_reports_patient({
            transaction
        });
        
        
        
        
        output.prescriptions_patient = await patient_profiles.getPrescriptions_patient({
            transaction
        });
        
        
        
        output.medicine_dispatches_to_patient = await patient_profiles.getMedicine_dispatches_to_patient({
            transaction
        });
        
        
        
        output.patient_vaccinations_patient = await patient_profiles.getPatient_vaccinations_patient({
            transaction
        });
        
        
        output.reminders_patient = await patient_profiles.getReminders_patient({
            transaction
        });
        
        
        output.chat_sessions_patient = await patient_profiles.getChat_sessions_patient({
            transaction
        });
        
        
        
        
        output.chatbot_interactions_patient = await patient_profiles.getChatbot_interactions_patient({
            transaction
        });
        
        
        output.feedbacks_patient = await patient_profiles.getFeedbacks_patient({
            transaction
        });
        
        
        
        output.user = await patient_profiles.getUser({
            transaction
        });
        
        
        output.registered_at_camp = await patient_profiles.getRegistered_at_camp({
            transaction
        });
        
        
        output.primary_rural_doctor = await patient_profiles.getPrimary_rural_doctor({
            transaction
        });
        
        
        output.identity_documents = await patient_profiles.getIdentity_documents({
            transaction
        });
        
        
        output.organizations = await patient_profiles.getOrganizations({
            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 userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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

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

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



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

    ];

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

            
            if (filter.patient_identifier) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'patient_profiles',
                        'patient_identifier',
                        filter.patient_identifier,
                    ),
                };
            }
            
            if (filter.blood_group) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'patient_profiles',
                        'blood_group',
                        filter.blood_group,
                    ),
                };
            }
            
            if (filter.address_line) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'patient_profiles',
                        'address_line',
                        filter.address_line,
                    ),
                };
            }
            
            if (filter.village) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'patient_profiles',
                        'village',
                        filter.village,
                    ),
                };
            }
            
            if (filter.district) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'patient_profiles',
                        'district',
                        filter.district,
                    ),
                };
            }
            
            if (filter.state) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'patient_profiles',
                        'state',
                        filter.state,
                    ),
                };
            }
            

            
            

            
            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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.gender) {
                where = {
                    ...where,
                gender: filter.gender,
            };
            }
            
            if (filter.consent_for_telemedicine) {
                where = {
                    ...where,
                consent_for_telemedicine: filter.consent_for_telemedicine,
            };
            }
            
            if (filter.consent_for_notifications) {
                where = {
                    ...where,
                consent_for_notifications: filter.consent_for_notifications,
            };
            }
            


      

      

      

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

        where = {
          ...where,
          organizationsId: {[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.organizationsId;
        }
        

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

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

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

    
};

