
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,
        
        visibility: data.visibility
        ||
        null
            ,
            
        output_title: data.output_title
        ||
        null
            ,
            
        output_text: data.output_text
        ||
        null
            ,
            
        generated_at: data.generated_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await ai_outputs.setAi_request( data.ai_request || null, {
            transaction,
        });
        
        await ai_outputs.setUser( data.user || 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,
                
                visibility: item.visibility
            ||
            null
            ,
            
                output_title: item.output_title
            ||
            null
            ,
            
                output_text: item.output_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 ai_outputs = await db.ai_outputs.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.visibility !== undefined) updatePayload.visibility = data.visibility;
        
        
        if (data.output_title !== undefined) updatePayload.output_title = data.output_title;
        
        
        if (data.output_text !== undefined) updatePayload.output_text = data.output_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_request !== undefined) {
            await ai_outputs.setAi_request(
              
              data.ai_request,
              
              { transaction }
            );
        }
        
        if (data.user !== undefined) {
            await ai_outputs.setUser(
              
              data.user,
              
              { 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.ai_request = await ai_outputs.getAi_request({
            transaction
        });
        
        
        output.user = await ai_outputs.getUser({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

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



    ];

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

            
            if (filter.output_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_outputs',
                        'output_title',
                        filter.output_title,
                    ),
                };
            }
            
            if (filter.output_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_outputs',
                        'output_text',
                        filter.output_text,
                    ),
                };
            }
            

            
            

            
            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.visibility) {
                where = {
                    ...where,
                visibility: filter.visibility,
            };
            }
            


      

      



            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,
                        },
                    };
                }
            }
        }
        

        

        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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'ai_outputs',
                        'output_title',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

