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

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

        const doctor_profiles = await db.doctor_profiles.create(
            {
                id: data.id || undefined,
        
        doctor_type: data.doctor_type
        ||
        null
            ,
            
        medical_license_number: data.medical_license_number
        ||
        null
            ,
            
        specialization: data.specialization
        ||
        null
            ,
            
        qualification: data.qualification
        ||
        null
            ,
            
        years_of_experience: data.years_of_experience
        ||
        null
            ,
            
        availability_status: data.availability_status
        ||
        null
            ,
            
        consultation_fee_note: data.consultation_fee_note
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await doctor_profiles.setUser( data.user || null, {
            transaction,
        });
        
        await doctor_profiles.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        

        

        

        return doctor_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 doctor_profilesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                doctor_type: item.doctor_type
            ||
            null
            ,
            
                medical_license_number: item.medical_license_number
            ||
            null
            ,
            
                specialization: item.specialization
            ||
            null
            ,
            
                qualification: item.qualification
            ||
            null
            ,
            
                years_of_experience: item.years_of_experience
            ||
            null
            ,
            
                availability_status: item.availability_status
            ||
            null
            ,
            
                consultation_fee_note: item.consultation_fee_note
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

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


        

        const updatePayload = {};
        
        if (data.doctor_type !== undefined) updatePayload.doctor_type = data.doctor_type;
        
        
        if (data.medical_license_number !== undefined) updatePayload.medical_license_number = data.medical_license_number;
        
        
        if (data.specialization !== undefined) updatePayload.specialization = data.specialization;
        
        
        if (data.qualification !== undefined) updatePayload.qualification = data.qualification;
        
        
        if (data.years_of_experience !== undefined) updatePayload.years_of_experience = data.years_of_experience;
        
        
        if (data.availability_status !== undefined) updatePayload.availability_status = data.availability_status;
        
        
        if (data.consultation_fee_note !== undefined) updatePayload.consultation_fee_note = data.consultation_fee_note;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await doctor_profiles.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.organization !== undefined) {
            await doctor_profiles.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        

        
        

        

        return doctor_profiles;
    }

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

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

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


        return doctor_profiles;
    }

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

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

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

        await doctor_profiles.destroy({
            transaction
        });

        return doctor_profiles;
    }

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

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

        if (!doctor_profiles) {
            return doctor_profiles;
        }

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

        
        
        
        
        
        
        output.patient_profiles_primary_rural_doctor = await doctor_profiles.getPatient_profiles_primary_rural_doctor({
            transaction
        });
        
        
        output.medical_camps_camp_lead_doctor = await doctor_profiles.getMedical_camps_camp_lead_doctor({
            transaction
        });
        
        
        output.appointments_doctor = await doctor_profiles.getAppointments_doctor({
            transaction
        });
        
        
        output.consultations_primary_doctor = await doctor_profiles.getConsultations_primary_doctor({
            transaction
        });
        
        output.consultations_secondary_doctor = await doctor_profiles.getConsultations_secondary_doctor({
            transaction
        });
        
        
        output.medical_reports_author_doctor = await doctor_profiles.getMedical_reports_author_doctor({
            transaction
        });
        
        
        
        
        output.prescriptions_prescribed_by_doctor = await doctor_profiles.getPrescriptions_prescribed_by_doctor({
            transaction
        });
        
        
        
        output.medicine_dispatches_dispatched_by_doctor = await doctor_profiles.getMedicine_dispatches_dispatched_by_doctor({
            transaction
        });
        
        
        
        
        
        output.chat_sessions_doctor = await doctor_profiles.getChat_sessions_doctor({
            transaction
        });
        
        output.chat_sessions_second_doctor = await doctor_profiles.getChat_sessions_second_doctor({
            transaction
        });
        
        
        
        
        
        output.feedbacks_doctor = await doctor_profiles.getFeedbacks_doctor({
            transaction
        });
        
        
        
        output.user = await doctor_profiles.getUser({
            transaction
        });
        
        
        output.organization = await doctor_profiles.getOrganization({
            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.organizations,
        as: 'organization',
        
      },



    ];

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

            
            if (filter.medical_license_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'doctor_profiles',
                        'medical_license_number',
                        filter.medical_license_number,
                    ),
                };
            }
            
            if (filter.specialization) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'doctor_profiles',
                        'specialization',
                        filter.specialization,
                    ),
                };
            }
            
            if (filter.qualification) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'doctor_profiles',
                        'qualification',
                        filter.qualification,
                    ),
                };
            }
            
            if (filter.consultation_fee_note) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'doctor_profiles',
                        'consultation_fee_note',
                        filter.consultation_fee_note,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.doctor_type) {
                where = {
                    ...where,
                doctor_type: filter.doctor_type,
            };
            }
            
            if (filter.availability_status) {
                where = {
                    ...where,
                availability_status: filter.availability_status,
            };
            }
            


      

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

        where = {
          ...where,
          organizationId: {[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.doctor_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(
                        'doctor_profiles',
                        'specialization',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

