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

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

        const chatbot_interactions = await db.chatbot_interactions.create(
            {
                id: data.id || undefined,
        
        asked_at: data.asked_at
        ||
        null
            ,
            
        user_prompt: data.user_prompt
        ||
        null
            ,
            
        ai_response: data.ai_response
        ||
        null
            ,
            
        model_name: data.model_name
        ||
        null
            ,
            
        confidence_score: data.confidence_score
        ||
        null
            ,
            
        triage_level: data.triage_level
        ||
        null
            ,
            
        escalated_to_doctor: data.escalated_to_doctor
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await chatbot_interactions.setPatient( data.patient || null, {
            transaction,
        });
        
        await chatbot_interactions.setChat_session( data.chat_session || null, {
            transaction,
        });
        
        await chatbot_interactions.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return chatbot_interactions;
    }
    

    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 chatbot_interactionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                asked_at: item.asked_at
            ||
            null
            ,
            
                user_prompt: item.user_prompt
            ||
            null
            ,
            
                ai_response: item.ai_response
            ||
            null
            ,
            
                model_name: item.model_name
            ||
            null
            ,
            
                confidence_score: item.confidence_score
            ||
            null
            ,
            
                triage_level: item.triage_level
            ||
            null
            ,
            
                escalated_to_doctor: item.escalated_to_doctor
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return chatbot_interactions;
    }

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


        

        const updatePayload = {};
        
        if (data.asked_at !== undefined) updatePayload.asked_at = data.asked_at;
        
        
        if (data.user_prompt !== undefined) updatePayload.user_prompt = data.user_prompt;
        
        
        if (data.ai_response !== undefined) updatePayload.ai_response = data.ai_response;
        
        
        if (data.model_name !== undefined) updatePayload.model_name = data.model_name;
        
        
        if (data.confidence_score !== undefined) updatePayload.confidence_score = data.confidence_score;
        
        
        if (data.triage_level !== undefined) updatePayload.triage_level = data.triage_level;
        
        
        if (data.escalated_to_doctor !== undefined) updatePayload.escalated_to_doctor = data.escalated_to_doctor;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.patient !== undefined) {
            await chatbot_interactions.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.chat_session !== undefined) {
            await chatbot_interactions.setChat_session(
              
              data.chat_session,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await chatbot_interactions.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return chatbot_interactions;
    }

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

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

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


        return chatbot_interactions;
    }

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

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

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

        await chatbot_interactions.destroy({
            transaction
        });

        return chatbot_interactions;
    }

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

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

        if (!chatbot_interactions) {
            return chatbot_interactions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.patient = await chatbot_interactions.getPatient({
            transaction
        });
        
        
        output.chat_session = await chatbot_interactions.getChat_session({
            transaction
        });
        
        
        output.organizations = await chatbot_interactions.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.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.chat_sessions,
        as: 'chat_session',
        
        where: filter.chat_session ? {
          [Op.or]: [
            { id: { [Op.in]: filter.chat_session.split('|').map(term => Utils.uuid(term)) } },
            {
              session_status: {
                [Op.or]: filter.chat_session.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.user_prompt) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'chatbot_interactions',
                        'user_prompt',
                        filter.user_prompt,
                    ),
                };
            }
            
            if (filter.ai_response) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'chatbot_interactions',
                        'ai_response',
                        filter.ai_response,
                    ),
                };
            }
            
            if (filter.model_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'chatbot_interactions',
                        'model_name',
                        filter.model_name,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.triage_level) {
                where = {
                    ...where,
                triage_level: filter.triage_level,
            };
            }
            
            if (filter.escalated_to_doctor) {
                where = {
                    ...where,
                escalated_to_doctor: filter.escalated_to_doctor,
            };
            }
            


      

      

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

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

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

    
};

