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

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

        const ai_mentor_profiles = await db.ai_mentor_profiles.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        persona: data.persona
        ||
        null
            ,
            
        system_prompt: data.system_prompt
        ||
        null
            ,
            
        tone: data.tone
        ||
        null
            ,
            
        supported_subjects: data.supported_subjects
        ||
        null
            ,
            
        visibility: data.visibility
        ||
        null
            ,
            
        is_default: data.is_default
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await ai_mentor_profiles.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        

        

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

        return ai_mentor_profiles;
    }
    

    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_mentor_profilesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                persona: item.persona
            ||
            null
            ,
            
                system_prompt: item.system_prompt
            ||
            null
            ,
            
                tone: item.tone
            ||
            null
            ,
            
                supported_subjects: item.supported_subjects
            ||
            null
            ,
            
                visibility: item.visibility
            ||
            null
            ,
            
                is_default: item.is_default
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return ai_mentor_profiles;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.persona !== undefined) updatePayload.persona = data.persona;
        
        
        if (data.system_prompt !== undefined) updatePayload.system_prompt = data.system_prompt;
        
        
        if (data.tone !== undefined) updatePayload.tone = data.tone;
        
        
        if (data.supported_subjects !== undefined) updatePayload.supported_subjects = data.supported_subjects;
        
        
        if (data.visibility !== undefined) updatePayload.visibility = data.visibility;
        
        
        if (data.is_default !== undefined) updatePayload.is_default = data.is_default;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await ai_mentor_profiles.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        

        
        

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

        return ai_mentor_profiles;
    }

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

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

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


        return ai_mentor_profiles;
    }

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

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

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

        await ai_mentor_profiles.destroy({
            transaction
        });

        return ai_mentor_profiles;
    }

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

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

        if (!ai_mentor_profiles) {
            return ai_mentor_profiles;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.mentor_conversations_mentor_profile = await ai_mentor_profiles.getMentor_conversations_mentor_profile({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await ai_mentor_profiles.getOrganization({
            transaction
        });
        
        
        output.avatar = await ai_mentor_profiles.getAvatar({
            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.organizations,
        as: 'organization',
        
      },



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

    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_mentor_profiles',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.persona) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_mentor_profiles',
                        'persona',
                        filter.persona,
                    ),
                };
            }
            
            if (filter.system_prompt) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_mentor_profiles',
                        'system_prompt',
                        filter.system_prompt,
                    ),
                };
            }
            
            if (filter.supported_subjects) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_mentor_profiles',
                        'supported_subjects',
                        filter.supported_subjects,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.tone) {
                where = {
                    ...where,
                tone: filter.tone,
            };
            }
            
            if (filter.visibility) {
                where = {
                    ...where,
                visibility: filter.visibility,
            };
            }
            
            if (filter.is_default) {
                where = {
                    ...where,
                is_default: filter.is_default,
            };
            }
            


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

        where = {
          ...where,
          organizationId: {[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_mentor_profiles.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_mentor_profiles',
                        'name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

