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

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

        const ai_tasks = await db.ai_tasks.create(
            {
                id: data.id || undefined,
        
        task_name: data.task_name
        ||
        null
            ,
            
        task_type: data.task_type
        ||
        null
            ,
            
        stores_private_output: data.stores_private_output
        ||
        false
        
            ,
            
        allowed_for_free_users: data.allowed_for_free_users
        ||
        false
        
            ,
            
        per_user_daily_limit: data.per_user_daily_limit
        ||
        null
            ,
            
        system_prompt_template: data.system_prompt_template
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return ai_tasks;
    }
    

    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_tasksData = data.map((item, index) => ({
                id: item.id || undefined,
                
                task_name: item.task_name
            ||
            null
            ,
            
                task_type: item.task_type
            ||
            null
            ,
            
                stores_private_output: item.stores_private_output
            ||
            false
        
            ,
            
                allowed_for_free_users: item.allowed_for_free_users
            ||
            false
        
            ,
            
                per_user_daily_limit: item.per_user_daily_limit
            ||
            null
            ,
            
                system_prompt_template: item.system_prompt_template
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return ai_tasks;
    }

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

        const ai_tasks = await db.ai_tasks.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.task_name !== undefined) updatePayload.task_name = data.task_name;
        
        
        if (data.task_type !== undefined) updatePayload.task_type = data.task_type;
        
        
        if (data.stores_private_output !== undefined) updatePayload.stores_private_output = data.stores_private_output;
        
        
        if (data.allowed_for_free_users !== undefined) updatePayload.allowed_for_free_users = data.allowed_for_free_users;
        
        
        if (data.per_user_daily_limit !== undefined) updatePayload.per_user_daily_limit = data.per_user_daily_limit;
        
        
        if (data.system_prompt_template !== undefined) updatePayload.system_prompt_template = data.system_prompt_template;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return ai_tasks;
    }

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

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

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


        return ai_tasks;
    }

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

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

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

        await ai_tasks.destroy({
            transaction
        });

        return ai_tasks;
    }

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

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

        if (!ai_tasks) {
            return ai_tasks;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.ai_requests_ai_task = await ai_tasks.getAi_requests_ai_task({
            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 = [



    ];

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

            
            if (filter.task_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_tasks',
                        'task_name',
                        filter.task_name,
                    ),
                };
            }
            
            if (filter.system_prompt_template) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_tasks',
                        'system_prompt_template',
                        filter.system_prompt_template,
                    ),
                };
            }
            

            
            

            
            if (filter.per_user_daily_limitRange) {
                const [start, end] = filter.per_user_daily_limitRange;

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

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

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

            
            if (filter.task_type) {
                where = {
                    ...where,
                task_type: filter.task_type,
            };
            }
            
            if (filter.stores_private_output) {
                where = {
                    ...where,
                stores_private_output: filter.stores_private_output,
            };
            }
            
            if (filter.allowed_for_free_users) {
                where = {
                    ...where,
                allowed_for_free_users: filter.allowed_for_free_users,
            };
            }
            




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

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

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

    
};

