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

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

        const city_doctors = await db.city_doctors.create(
            {
                id: data.id || undefined,
        
        full_name: data.full_name
        ||
        null
            ,
            
        hospital_code: data.hospital_code
        ||
        null
            ,
            
        doctor_registration_no: data.doctor_registration_no
        ||
        null
            ,
            
        specialization: data.specialization
        ||
        null
            ,
            
        years_experience: data.years_experience
        ||
        null
            ,
            
        qualification: data.qualification
        ||
        null
            ,
            
        availability_status: data.availability_status
        ||
        null
            ,
            
        consultation_fee: data.consultation_fee
        ||
        null
            ,
            
        clinic_address: data.clinic_address
        ||
        null
            ,
            
        clinic_latitude: data.clinic_latitude
        ||
        null
            ,
            
        clinic_longitude: data.clinic_longitude
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return city_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 city_doctorsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                full_name: item.full_name
            ||
            null
            ,
            
                hospital_code: item.hospital_code
            ||
            null
            ,
            
                doctor_registration_no: item.doctor_registration_no
            ||
            null
            ,
            
                specialization: item.specialization
            ||
            null
            ,
            
                years_experience: item.years_experience
            ||
            null
            ,
            
                qualification: item.qualification
            ||
            null
            ,
            
                availability_status: item.availability_status
            ||
            null
            ,
            
                consultation_fee: item.consultation_fee
            ||
            null
            ,
            
                clinic_address: item.clinic_address
            ||
            null
            ,
            
                clinic_latitude: item.clinic_latitude
            ||
            null
            ,
            
                clinic_longitude: item.clinic_longitude
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return city_doctors;
    }

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

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


        

        const updatePayload = {};
        
        if (data.full_name !== undefined) updatePayload.full_name = data.full_name;
        
        
        if (data.hospital_code !== undefined) updatePayload.hospital_code = data.hospital_code;
        
        
        if (data.doctor_registration_no !== undefined) updatePayload.doctor_registration_no = data.doctor_registration_no;
        
        
        if (data.specialization !== undefined) updatePayload.specialization = data.specialization;
        
        
        if (data.years_experience !== undefined) updatePayload.years_experience = data.years_experience;
        
        
        if (data.qualification !== undefined) updatePayload.qualification = data.qualification;
        
        
        if (data.availability_status !== undefined) updatePayload.availability_status = data.availability_status;
        
        
        if (data.consultation_fee !== undefined) updatePayload.consultation_fee = data.consultation_fee;
        
        
        if (data.clinic_address !== undefined) updatePayload.clinic_address = data.clinic_address;
        
        
        if (data.clinic_latitude !== undefined) updatePayload.clinic_latitude = data.clinic_latitude;
        
        
        if (data.clinic_longitude !== undefined) updatePayload.clinic_longitude = data.clinic_longitude;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return city_doctors;
    }

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

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

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


        return city_doctors;
    }

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

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

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

        await city_doctors.destroy({
            transaction
        });

        return city_doctors;
    }

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

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

        if (!city_doctors) {
            return city_doctors;
        }

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

        
        
        
        
        
        
        
        
        output.medical_reports_author_city_doctor = await city_doctors.getMedical_reports_author_city_doctor({
            transaction
        });
        
        
        
        
        output.medicine_dispatches_coordinated_by_city_doctor = await city_doctors.getMedicine_dispatches_coordinated_by_city_doctor({
            transaction
        });
        
        
        
        output.medical_camps_lead_city_doctor = await city_doctors.getMedical_camps_lead_city_doctor({
            transaction
        });
        
        
        output.appointments_city_doctor = await city_doctors.getAppointments_city_doctor({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await city_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(
                        'city_doctors',
                        'full_name',
                        filter.full_name,
                    ),
                };
            }
            
            if (filter.hospital_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'city_doctors',
                        'hospital_code',
                        filter.hospital_code,
                    ),
                };
            }
            
            if (filter.doctor_registration_no) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'city_doctors',
                        'doctor_registration_no',
                        filter.doctor_registration_no,
                    ),
                };
            }
            
            if (filter.specialization) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'city_doctors',
                        'specialization',
                        filter.specialization,
                    ),
                };
            }
            
            if (filter.qualification) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'city_doctors',
                        'qualification',
                        filter.qualification,
                    ),
                };
            }
            
            if (filter.clinic_address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'city_doctors',
                        'clinic_address',
                        filter.clinic_address,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    clinic_longitude: {
                    ...where.clinic_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.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.city_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(
                        'city_doctors',
                        'full_name',
                        query,
                    ),
                ],
            };
        }

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

    
};

