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

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

        const rural_doctors = await db.rural_doctors.create(
            {
                id: data.id || undefined,
        
        full_name: data.full_name
        ||
        null
            ,
            
        dho_code: data.dho_code
        ||
        null
            ,
            
        doctor_registration_no: data.doctor_registration_no
        ||
        null
            ,
            
        assigned_region: data.assigned_region
        ||
        null
            ,
            
        subcenter_name: data.subcenter_name
        ||
        null
            ,
            
        subcenter_latitude: data.subcenter_latitude
        ||
        null
            ,
            
        subcenter_longitude: data.subcenter_longitude
        ||
        null
            ,
            
        availability_status: data.availability_status
        ||
        null
            ,
            
        can_register_patients: data.can_register_patients
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await rural_doctors.setUser( data.user || null, {
            transaction,
        });
        

        

        

        return rural_doctors;
    }
    

    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 rural_doctorsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                full_name: item.full_name
            ||
            null
            ,
            
                dho_code: item.dho_code
            ||
            null
            ,
            
                doctor_registration_no: item.doctor_registration_no
            ||
            null
            ,
            
                assigned_region: item.assigned_region
            ||
            null
            ,
            
                subcenter_name: item.subcenter_name
            ||
            null
            ,
            
                subcenter_latitude: item.subcenter_latitude
            ||
            null
            ,
            
                subcenter_longitude: item.subcenter_longitude
            ||
            null
            ,
            
                availability_status: item.availability_status
            ||
            null
            ,
            
                can_register_patients: item.can_register_patients
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return rural_doctors;
    }

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

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


        

        const updatePayload = {};
        
        if (data.full_name !== undefined) updatePayload.full_name = data.full_name;
        
        
        if (data.dho_code !== undefined) updatePayload.dho_code = data.dho_code;
        
        
        if (data.doctor_registration_no !== undefined) updatePayload.doctor_registration_no = data.doctor_registration_no;
        
        
        if (data.assigned_region !== undefined) updatePayload.assigned_region = data.assigned_region;
        
        
        if (data.subcenter_name !== undefined) updatePayload.subcenter_name = data.subcenter_name;
        
        
        if (data.subcenter_latitude !== undefined) updatePayload.subcenter_latitude = data.subcenter_latitude;
        
        
        if (data.subcenter_longitude !== undefined) updatePayload.subcenter_longitude = data.subcenter_longitude;
        
        
        if (data.availability_status !== undefined) updatePayload.availability_status = data.availability_status;
        
        
        if (data.can_register_patients !== undefined) updatePayload.can_register_patients = data.can_register_patients;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return rural_doctors;
    }

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

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

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


        return rural_doctors;
    }

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

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

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

        await rural_doctors.destroy({
            transaction
        });

        return rural_doctors;
    }

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

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

        if (!rural_doctors) {
            return rural_doctors;
        }

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

        
        
        
        
        
        
        
        output.patients_registered_by_rural_doctor = await rural_doctors.getPatients_registered_by_rural_doctor({
            transaction
        });
        
        
        output.medical_reports_author_rural_doctor = await rural_doctors.getMedical_reports_author_rural_doctor({
            transaction
        });
        
        
        
        output.inventory_updates_rural_doctor = await rural_doctors.getInventory_updates_rural_doctor({
            transaction
        });
        
        
        output.medicine_dispatches_requested_by_rural_doctor = await rural_doctors.getMedicine_dispatches_requested_by_rural_doctor({
            transaction
        });
        
        
        
        output.medical_camps_lead_rural_doctor = await rural_doctors.getMedical_camps_lead_rural_doctor({
            transaction
        });
        
        
        output.appointments_rural_doctor = await rural_doctors.getAppointments_rural_doctor({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await rural_doctors.getUser({
            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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.full_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'rural_doctors',
                        'full_name',
                        filter.full_name,
                    ),
                };
            }
            
            if (filter.dho_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'rural_doctors',
                        'dho_code',
                        filter.dho_code,
                    ),
                };
            }
            
            if (filter.doctor_registration_no) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'rural_doctors',
                        'doctor_registration_no',
                        filter.doctor_registration_no,
                    ),
                };
            }
            
            if (filter.assigned_region) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'rural_doctors',
                        'assigned_region',
                        filter.assigned_region,
                    ),
                };
            }
            
            if (filter.subcenter_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'rural_doctors',
                        'subcenter_name',
                        filter.subcenter_name,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      



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

        const records = await db.rural_doctors.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,
        }));
    }

    
};

