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

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

        const consultations = await db.consultations.create(
            {
                id: data.id || undefined,
        
        started_at: data.started_at
        ||
        null
            ,
            
        ended_at: data.ended_at
        ||
        null
            ,
            
        channel: data.channel
        ||
        null
            ,
            
        consultation_status: data.consultation_status
        ||
        null
            ,
            
        chief_complaint: data.chief_complaint
        ||
        null
            ,
            
        clinical_notes: data.clinical_notes
        ||
        null
            ,
            
        diagnosis_summary: data.diagnosis_summary
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await consultations.setAppointment( data.appointment || null, {
            transaction,
        });
        
        await consultations.setPatient( data.patient || null, {
            transaction,
        });
        
        await consultations.setPrimary_doctor( data.primary_doctor || null, {
            transaction,
        });
        
        await consultations.setSecondary_doctor( data.secondary_doctor || null, {
            transaction,
        });
        
        await consultations.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.consultations.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: consultations.id,
            },
            data.attachments,
            options,
        );
        

        return consultations;
    }
    

    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 consultationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                started_at: item.started_at
            ||
            null
            ,
            
                ended_at: item.ended_at
            ||
            null
            ,
            
                channel: item.channel
            ||
            null
            ,
            
                consultation_status: item.consultation_status
            ||
            null
            ,
            
                chief_complaint: item.chief_complaint
            ||
            null
            ,
            
                clinical_notes: item.clinical_notes
            ||
            null
            ,
            
                diagnosis_summary: item.diagnosis_summary
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < consultations.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.consultations.getTableName(),
                    belongsToColumn: 'attachments',
                    belongsToId: consultations[i].id,
                },
                data[i].attachments,
                options,
            );
        }
        

        return consultations;
    }

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


        

        const updatePayload = {};
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
        
        
        if (data.channel !== undefined) updatePayload.channel = data.channel;
        
        
        if (data.consultation_status !== undefined) updatePayload.consultation_status = data.consultation_status;
        
        
        if (data.chief_complaint !== undefined) updatePayload.chief_complaint = data.chief_complaint;
        
        
        if (data.clinical_notes !== undefined) updatePayload.clinical_notes = data.clinical_notes;
        
        
        if (data.diagnosis_summary !== undefined) updatePayload.diagnosis_summary = data.diagnosis_summary;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.appointment !== undefined) {
            await consultations.setAppointment(
              
              data.appointment,
              
              { transaction }
            );
        }
        
        if (data.patient !== undefined) {
            await consultations.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.primary_doctor !== undefined) {
            await consultations.setPrimary_doctor(
              
              data.primary_doctor,
              
              { transaction }
            );
        }
        
        if (data.secondary_doctor !== undefined) {
            await consultations.setSecondary_doctor(
              
              data.secondary_doctor,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await consultations.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.consultations.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: consultations.id,
            },
            data.attachments,
            options,
        );
        

        return consultations;
    }

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

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

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


        return consultations;
    }

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

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

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

        await consultations.destroy({
            transaction
        });

        return consultations;
    }

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

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

        if (!consultations) {
            return consultations;
        }

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

        
        
        
        
        
        
        
        
        
        
        output.medical_reports_consultation = await consultations.getMedical_reports_consultation({
            transaction
        });
        
        
        
        
        output.prescriptions_consultation = await consultations.getPrescriptions_consultation({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.video_calls_consultation = await consultations.getVideo_calls_consultation({
            transaction
        });
        
        
        
        output.feedbacks_consultation = await consultations.getFeedbacks_consultation({
            transaction
        });
        
        
        
        output.appointment = await consultations.getAppointment({
            transaction
        });
        
        
        output.patient = await consultations.getPatient({
            transaction
        });
        
        
        output.primary_doctor = await consultations.getPrimary_doctor({
            transaction
        });
        
        
        output.secondary_doctor = await consultations.getSecondary_doctor({
            transaction
        });
        
        
        output.attachments = await consultations.getAttachments({
            transaction
        });
        
        
        output.organizations = await consultations.getOrganizations({
            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.appointments,
        as: 'appointment',
        
        where: filter.appointment ? {
          [Op.or]: [
            { id: { [Op.in]: filter.appointment.split('|').map(term => Utils.uuid(term)) } },
            {
              reason: {
                [Op.or]: filter.appointment.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.patient_profiles,
        as: 'patient',
        
        where: filter.patient ? {
          [Op.or]: [
            { id: { [Op.in]: filter.patient.split('|').map(term => Utils.uuid(term)) } },
            {
              patient_identifier: {
                [Op.or]: filter.patient.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.doctor_profiles,
        as: 'primary_doctor',
        
        where: filter.primary_doctor ? {
          [Op.or]: [
            { id: { [Op.in]: filter.primary_doctor.split('|').map(term => Utils.uuid(term)) } },
            {
              specialization: {
                [Op.or]: filter.primary_doctor.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.doctor_profiles,
        as: 'secondary_doctor',
        
        where: filter.secondary_doctor ? {
          [Op.or]: [
            { id: { [Op.in]: filter.secondary_doctor.split('|').map(term => Utils.uuid(term)) } },
            {
              specialization: {
                [Op.or]: filter.secondary_doctor.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.organizations,
        as: 'organizations',
        
      },



      {
        model: db.file,
        as: 'attachments',
      },

    ];

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

            
            if (filter.chief_complaint) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'consultations',
                        'chief_complaint',
                        filter.chief_complaint,
                    ),
                };
            }
            
            if (filter.clinical_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'consultations',
                        'clinical_notes',
                        filter.clinical_notes,
                    ),
                };
            }
            
            if (filter.diagnosis_summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'consultations',
                        'diagnosis_summary',
                        filter.diagnosis_summary,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.channel) {
                where = {
                    ...where,
                channel: filter.channel,
            };
            }
            
            if (filter.consultation_status) {
                where = {
                    ...where,
                consultation_status: filter.consultation_status,
            };
            }
            


      

      

      

      

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

        where = {
          ...where,
          organizationsId: {[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.consultations.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(
                        'consultations',
                        'chief_complaint',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

