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

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

        const ai_outputs = await db.ai_outputs.create(
            {
                id: data.id || undefined,
        
        output_type: data.output_type
        ||
        null
            ,
            
        output_json: data.output_json
        ||
        null
            ,
            
        confidence_score: data.confidence_score
        ||
        null
            ,
            
        citations_json: data.citations_json
        ||
        null
            ,
            
        model_ref: data.model_ref
        ||
        null
            ,
            
        prompt_text: data.prompt_text
        ||
        null
            ,
            
        generated_at: data.generated_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await ai_outputs.setAi_job( data.ai_job || null, {
            transaction,
        });
        
        await ai_outputs.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return ai_outputs;
    }
    

    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_outputsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                output_type: item.output_type
            ||
            null
            ,
            
                output_json: item.output_json
            ||
            null
            ,
            
                confidence_score: item.confidence_score
            ||
            null
            ,
            
                citations_json: item.citations_json
            ||
            null
            ,
            
                model_ref: item.model_ref
            ||
            null
            ,
            
                prompt_text: item.prompt_text
            ||
            null
            ,
            
                generated_at: item.generated_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return ai_outputs;
    }

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


        

        const updatePayload = {};
        
        if (data.output_type !== undefined) updatePayload.output_type = data.output_type;
        
        
        if (data.output_json !== undefined) updatePayload.output_json = data.output_json;
        
        
        if (data.confidence_score !== undefined) updatePayload.confidence_score = data.confidence_score;
        
        
        if (data.citations_json !== undefined) updatePayload.citations_json = data.citations_json;
        
        
        if (data.model_ref !== undefined) updatePayload.model_ref = data.model_ref;
        
        
        if (data.prompt_text !== undefined) updatePayload.prompt_text = data.prompt_text;
        
        
        if (data.generated_at !== undefined) updatePayload.generated_at = data.generated_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.ai_job !== undefined) {
            await ai_outputs.setAi_job(
              
              data.ai_job,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await ai_outputs.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return ai_outputs;
    }

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

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

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


        return ai_outputs;
    }

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

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

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

        await ai_outputs.destroy({
            transaction
        });

        return ai_outputs;
    }

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

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

        if (!ai_outputs) {
            return ai_outputs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.review_actions_ai_output = await ai_outputs.getReview_actions_ai_output({
            transaction
        });
        
        
        
        
        
        
        output.ai_job = await ai_outputs.getAi_job({
            transaction
        });
        
        
        output.organizations = await ai_outputs.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.ai_jobs,
        as: 'ai_job',
        
        where: filter.ai_job ? {
          [Op.or]: [
            { id: { [Op.in]: filter.ai_job.split('|').map(term => Utils.uuid(term)) } },
            {
              model_ref: {
                [Op.or]: filter.ai_job.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.output_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_outputs',
                        'output_json',
                        filter.output_json,
                    ),
                };
            }
            
            if (filter.citations_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_outputs',
                        'citations_json',
                        filter.citations_json,
                    ),
                };
            }
            
            if (filter.model_ref) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_outputs',
                        'model_ref',
                        filter.model_ref,
                    ),
                };
            }
            
            if (filter.prompt_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_outputs',
                        'prompt_text',
                        filter.prompt_text,
                    ),
                };
            }
            

            
            

            
            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.generated_atRange) {
                const [start, end] = filter.generated_atRange;

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

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

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

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


      

      
      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_outputs.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_outputs',
                        'model_ref',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

