
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_uid: data.patient_uid
        ||
        null
            ,
            
        full_name: data.full_name
        ||
        null
            ,
            
        gender: data.gender
        ||
        null
            ,
            
        date_of_birth: data.date_of_birth
        ||
        null
            ,
            
        blood_group: data.blood_group
        ||
        null
            ,
            
        allergies: data.allergies
        ||
        null
            ,
            
        chronic_conditions: data.chronic_conditions
        ||
        null
            ,
            
        emergency_contact_name: data.emergency_contact_name
        ||
        null
            ,
            
        emergency_contact_phone: data.emergency_contact_phone
        ||
        null
            ,
            
        registered_at: data.registered_at
        ||
        null
            ,
            
        account_status: data.account_status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await patients.setUser( data.user || null, {
            transaction,
        });
        
        await patients.setRegistered_by_rural_doctor( data.registered_by_rural_doctor || null, {
            transaction,
        });
        

        

        

        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_uid: item.patient_uid
            ||
            null
            ,
            
                full_name: item.full_name
            ||
            null
            ,
            
                gender: item.gender
            ||
            null
            ,
            
                date_of_birth: item.date_of_birth
            ||
            null
            ,
            
                blood_group: item.blood_group
            ||
            null
            ,
            
                allergies: item.allergies
            ||
            null
            ,
            
                chronic_conditions: item.chronic_conditions
            ||
            null
            ,
            
                emergency_contact_name: item.emergency_contact_name
            ||
            null
            ,
            
                emergency_contact_phone: item.emergency_contact_phone
            ||
            null
            ,
            
                registered_at: item.registered_at
            ||
            null
            ,
            
                account_status: item.account_status
            ||
            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
        

        return patients;
    }

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

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


        

        const updatePayload = {};
        
        if (data.patient_uid !== undefined) updatePayload.patient_uid = data.patient_uid;
        
        
        if (data.full_name !== undefined) updatePayload.full_name = data.full_name;
        
        
        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.allergies !== undefined) updatePayload.allergies = data.allergies;
        
        
        if (data.chronic_conditions !== undefined) updatePayload.chronic_conditions = data.chronic_conditions;
        
        
        if (data.emergency_contact_name !== undefined) updatePayload.emergency_contact_name = data.emergency_contact_name;
        
        
        if (data.emergency_contact_phone !== undefined) updatePayload.emergency_contact_phone = data.emergency_contact_phone;
        
        
        if (data.registered_at !== undefined) updatePayload.registered_at = data.registered_at;
        
        
        if (data.account_status !== undefined) updatePayload.account_status = data.account_status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await patients.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.registered_by_rural_doctor !== undefined) {
            await patients.setRegistered_by_rural_doctor(
              
              data.registered_by_rural_doctor,
              
              { transaction }
            );
        }
        

        
        

        

        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.medical_reports_patient = await patients.getMedical_reports_patient({
            transaction
        });
        
        
        
        
        
        
        
        output.appointments_patient = await patients.getAppointments_patient({
            transaction
        });
        
        
        
        
        
        
        
        output.vaccination_reminders_patient = await patients.getVaccination_reminders_patient({
            transaction
        });
        
        
        output.medicine_reminders_patient = await patients.getMedicine_reminders_patient({
            transaction
        });
        
        
        output.ai_chat_sessions_patient = await patients.getAi_chat_sessions_patient({
            transaction
        });
        
        
        
        
        
        output.user = await patients.getUser({
            transaction
        });
        
        
        output.registered_by_rural_doctor = await patients.getRegistered_by_rural_doctor({
            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.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.rural_doctors,
        as: 'registered_by_rural_doctor',
        
        where: filter.registered_by_rural_doctor ? {
          [Op.or]: [
            { id: { [Op.in]: filter.registered_by_rural_doctor.split('|').map(term => Utils.uuid(term)) } },
            {
              full_name: {
                [Op.or]: filter.registered_by_rural_doctor.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.patient_uid) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'patients',
                        'patient_uid',
                        filter.patient_uid,
                    ),
                };
            }
            
            if (filter.full_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'patients',
                        'full_name',
                        filter.full_name,
                    ),
                };
            }
            
            if (filter.blood_group) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'patients',
                        'blood_group',
                        filter.blood_group,
                    ),
                };
            }
            
            if (filter.allergies) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'patients',
                        'allergies',
                        filter.allergies,
                    ),
                };
            }
            
            if (filter.chronic_conditions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'patients',
                        'chronic_conditions',
                        filter.chronic_conditions,
                    ),
                };
            }
            
            if (filter.emergency_contact_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'patients',
                        'emergency_contact_name',
                        filter.emergency_contact_name,
                    ),
                };
            }
            
            if (filter.emergency_contact_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'patients',
                        'emergency_contact_phone',
                        filter.emergency_contact_phone,
                    ),
                };
            }
            

            
            

            
            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.registered_atRange) {
                const [start, end] = filter.registered_atRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    registered_at: {
                    ...where.registered_at,
                            [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.account_status) {
                where = {
                    ...where,
                account_status: filter.account_status,
            };
            }
            


      

      



            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.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, ) {
        let where = {};
        
        

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

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

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

    
};

