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

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

        const ai_companion_sessions = await db.ai_companion_sessions.create(
            {
                id: data.id || undefined,
        
        companion_status: data.companion_status
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        ended_at: data.ended_at
        ||
        null
            ,
            
        auto_actions_enabled: data.auto_actions_enabled
        ||
        false
        
            ,
            
        system_prompt_version: data.system_prompt_version
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await ai_companion_sessions.setConference( data.conference || null, {
            transaction,
        });
        
        await ai_companion_sessions.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return ai_companion_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 ai_companion_sessionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                companion_status: item.companion_status
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                ended_at: item.ended_at
            ||
            null
            ,
            
                auto_actions_enabled: item.auto_actions_enabled
            ||
            false
        
            ,
            
                system_prompt_version: item.system_prompt_version
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

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


        

        const updatePayload = {};
        
        if (data.companion_status !== undefined) updatePayload.companion_status = data.companion_status;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
        
        
        if (data.auto_actions_enabled !== undefined) updatePayload.auto_actions_enabled = data.auto_actions_enabled;
        
        
        if (data.system_prompt_version !== undefined) updatePayload.system_prompt_version = data.system_prompt_version;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.conference !== undefined) {
            await ai_companion_sessions.setConference(
              
              data.conference,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await ai_companion_sessions.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return ai_companion_sessions;
    }

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

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

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


        return ai_companion_sessions;
    }

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

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

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

        await ai_companion_sessions.destroy({
            transaction
        });

        return ai_companion_sessions;
    }

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

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

        if (!ai_companion_sessions) {
            return ai_companion_sessions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.knowledge_graph_items_ai_companion_session = await ai_companion_sessions.getKnowledge_graph_items_ai_companion_session({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.conference = await ai_companion_sessions.getConference({
            transaction
        });
        
        
        output.organizations = await ai_companion_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.conferences,
        as: 'conference',
        
        where: filter.conference ? {
          [Op.or]: [
            { id: { [Op.in]: filter.conference.split('|').map(term => Utils.uuid(term)) } },
            {
              conference_key: {
                [Op.or]: filter.conference.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.system_prompt_version) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_companion_sessions',
                        'system_prompt_version',
                        filter.system_prompt_version,
                    ),
                };
            }
            

            
            

            
            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.companion_status) {
                where = {
                    ...where,
                companion_status: filter.companion_status,
            };
            }
            
            if (filter.auto_actions_enabled) {
                where = {
                    ...where,
                auto_actions_enabled: filter.auto_actions_enabled,
            };
            }
            


      

      
      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.ai_companion_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(
                        'ai_companion_sessions',
                        'companion_status',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

