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

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

        const chat_sessions = await db.chat_sessions.create(
            {
                id: data.id || undefined,
        
        session_type: data.session_type
        ||
        null
            ,
            
        session_status: data.session_status
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        ended_at: data.ended_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await chat_sessions.setPatient( data.patient || null, {
            transaction,
        });
        
        await chat_sessions.setDoctor( data.doctor || null, {
            transaction,
        });
        
        await chat_sessions.setSecond_doctor( data.second_doctor || null, {
            transaction,
        });
        
        await chat_sessions.setCreated_by_user( data.created_by_user || null, {
            transaction,
        });
        
        await chat_sessions.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return chat_sessions;
    }
    

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

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

        // For each item created, replace relation files
        

        return chat_sessions;
    }

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


        

        const updatePayload = {};
        
        if (data.session_type !== undefined) updatePayload.session_type = data.session_type;
        
        
        if (data.session_status !== undefined) updatePayload.session_status = data.session_status;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.patient !== undefined) {
            await chat_sessions.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.doctor !== undefined) {
            await chat_sessions.setDoctor(
              
              data.doctor,
              
              { transaction }
            );
        }
        
        if (data.second_doctor !== undefined) {
            await chat_sessions.setSecond_doctor(
              
              data.second_doctor,
              
              { transaction }
            );
        }
        
        if (data.created_by_user !== undefined) {
            await chat_sessions.setCreated_by_user(
              
              data.created_by_user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await chat_sessions.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return chat_sessions;
    }

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

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

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


        return chat_sessions;
    }

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

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

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

        await chat_sessions.destroy({
            transaction
        });

        return chat_sessions;
    }

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

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

        if (!chat_sessions) {
            return chat_sessions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.messages_chat_session = await chat_sessions.getMessages_chat_session({
            transaction
        });
        
        
        output.video_calls_chat_session = await chat_sessions.getVideo_calls_chat_session({
            transaction
        });
        
        
        output.chatbot_interactions_chat_session = await chat_sessions.getChatbot_interactions_chat_session({
            transaction
        });
        
        
        
        
        output.patient = await chat_sessions.getPatient({
            transaction
        });
        
        
        output.doctor = await chat_sessions.getDoctor({
            transaction
        });
        
        
        output.second_doctor = await chat_sessions.getSecond_doctor({
            transaction
        });
        
        
        output.created_by_user = await chat_sessions.getCreated_by_user({
            transaction
        });
        
        
        output.organizations = await chat_sessions.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.doctor_profiles,
        as: 'doctor',
        
        where: filter.doctor ? {
          [Op.or]: [
            { id: { [Op.in]: filter.doctor.split('|').map(term => Utils.uuid(term)) } },
            {
              specialization: {
                [Op.or]: filter.doctor.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        model: db.users,
        as: 'created_by_user',
        
        where: filter.created_by_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.created_by_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.created_by_user.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.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.session_type) {
                where = {
                    ...where,
                session_type: filter.session_type,
            };
            }
            
            if (filter.session_status) {
                where = {
                    ...where,
                session_status: filter.session_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.chat_sessions.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(
                        'chat_sessions',
                        'session_status',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

