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

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

        const healthcare_providers = await db.healthcare_providers.create(
            {
                id: data.id || undefined,
        
        provider_type: data.provider_type
        ||
        null
            ,
            
        provider_name: data.provider_name
        ||
        null
            ,
            
        clinic_name: data.clinic_name
        ||
        null
            ,
            
        phone: data.phone
        ||
        null
            ,
            
        email: data.email
        ||
        null
            ,
            
        address: data.address
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return healthcare_providers;
    }
    

    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 healthcare_providersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                provider_type: item.provider_type
            ||
            null
            ,
            
                provider_name: item.provider_name
            ||
            null
            ,
            
                clinic_name: item.clinic_name
            ||
            null
            ,
            
                phone: item.phone
            ||
            null
            ,
            
                email: item.email
            ||
            null
            ,
            
                address: item.address
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return healthcare_providers;
    }

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

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


        

        const updatePayload = {};
        
        if (data.provider_type !== undefined) updatePayload.provider_type = data.provider_type;
        
        
        if (data.provider_name !== undefined) updatePayload.provider_name = data.provider_name;
        
        
        if (data.clinic_name !== undefined) updatePayload.clinic_name = data.clinic_name;
        
        
        if (data.phone !== undefined) updatePayload.phone = data.phone;
        
        
        if (data.email !== undefined) updatePayload.email = data.email;
        
        
        if (data.address !== undefined) updatePayload.address = data.address;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return healthcare_providers;
    }

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

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

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


        return healthcare_providers;
    }

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

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

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

        await healthcare_providers.destroy({
            transaction
        });

        return healthcare_providers;
    }

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

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

        if (!healthcare_providers) {
            return healthcare_providers;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.medications_prescribing_provider = await healthcare_providers.getMedications_prescribing_provider({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.medical_appointments_provider = await healthcare_providers.getMedical_appointments_provider({
            transaction
        });
        
        
        output.lab_documents_ordered_by_provider = await healthcare_providers.getLab_documents_ordered_by_provider({
            transaction
        });
        
        
        output.vaccinations_provider = await healthcare_providers.getVaccinations_provider({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.sti_tests_clinic_provider = await healthcare_providers.getSti_tests_clinic_provider({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.vision_prescriptions_optometrist = await healthcare_providers.getVision_prescriptions_optometrist({
            transaction
        });
        
        
        
        output.hearing_test_logs_provider = await healthcare_providers.getHearing_test_logs_provider({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await healthcare_providers.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.provider_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'healthcare_providers',
                        'provider_name',
                        filter.provider_name,
                    ),
                };
            }
            
            if (filter.clinic_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'healthcare_providers',
                        'clinic_name',
                        filter.clinic_name,
                    ),
                };
            }
            
            if (filter.phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'healthcare_providers',
                        'phone',
                        filter.phone,
                    ),
                };
            }
            
            if (filter.email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'healthcare_providers',
                        'email',
                        filter.email,
                    ),
                };
            }
            
            if (filter.address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'healthcare_providers',
                        'address',
                        filter.address,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'healthcare_providers',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.provider_type) {
                where = {
                    ...where,
                provider_type: filter.provider_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.healthcare_providers.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(
                        'healthcare_providers',
                        'provider_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

