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

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

        const doctors = await db.doctors.create(
            {
                id: data.id || undefined,
        
        full_name: data.full_name
        ||
        null
            ,
            
        national_number: data.national_number
        ||
        null
            ,
            
        hire_date: data.hire_date
        ||
        null
            ,
            
        specialty: data.specialty
        ||
        null
            ,
            
        visit_price: data.visit_price
        ||
        null
            ,
            
        doctor_type: data.doctor_type
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await doctors.setUser_account( data.user_account || null, {
            transaction,
        });
        

        

        

        return 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 doctorsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                full_name: item.full_name
            ||
            null
            ,
            
                national_number: item.national_number
            ||
            null
            ,
            
                hire_date: item.hire_date
            ||
            null
            ,
            
                specialty: item.specialty
            ||
            null
            ,
            
                visit_price: item.visit_price
            ||
            null
            ,
            
                doctor_type: item.doctor_type
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return doctors;
    }

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

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


        

        const updatePayload = {};
        
        if (data.full_name !== undefined) updatePayload.full_name = data.full_name;
        
        
        if (data.national_number !== undefined) updatePayload.national_number = data.national_number;
        
        
        if (data.hire_date !== undefined) updatePayload.hire_date = data.hire_date;
        
        
        if (data.specialty !== undefined) updatePayload.specialty = data.specialty;
        
        
        if (data.visit_price !== undefined) updatePayload.visit_price = data.visit_price;
        
        
        if (data.doctor_type !== undefined) updatePayload.doctor_type = data.doctor_type;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user_account !== undefined) {
            await doctors.setUser_account(
              
              data.user_account,
              
              { transaction }
            );
        }
        

        
        

        

        return doctors;
    }

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

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

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


        return doctors;
    }

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

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

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

        await doctors.destroy({
            transaction
        });

        return doctors;
    }

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

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

        if (!doctors) {
            return doctors;
        }

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

        
        
        
        
        output.patients_primary_doctor = await doctors.getPatients_primary_doctor({
            transaction
        });
        
        
        
        
        output.visits_doctor = await doctors.getVisits_doctor({
            transaction
        });
        
        
        output.orders_requested_by = await doctors.getOrders_requested_by({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.endoscopy_cases_doctor = await doctors.getEndoscopy_cases_doctor({
            transaction
        });
        
        
        output.surgery_cases_surgeon = await doctors.getSurgery_cases_surgeon({
            transaction
        });
        
        
        
        
        output.cathlab_cases_doctor = await doctors.getCathlab_cases_doctor({
            transaction
        });
        
        
        output.ecg_stress_tests_doctor = await doctors.getEcg_stress_tests_doctor({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.room_bookings_supervising_doctor = await doctors.getRoom_bookings_supervising_doctor({
            transaction
        });
        
        
        
        
        output.maternity_cases_doctor = await doctors.getMaternity_cases_doctor({
            transaction
        });
        
        
        
        output.nicu_incubators_admitting_doctor = await doctors.getNicu_incubators_admitting_doctor({
            transaction
        });
        
        
        
        
        
        
        output.user_account = await doctors.getUser_account({
            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_account',
        
        where: filter.user_account ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user_account.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user_account.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(
                        'doctors',
                        'full_name',
                        filter.full_name,
                    ),
                };
            }
            
            if (filter.national_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'doctors',
                        'national_number',
                        filter.national_number,
                    ),
                };
            }
            
            if (filter.specialty) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'doctors',
                        'specialty',
                        filter.specialty,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

    
};

