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

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

        const ai_insight_runs = await db.ai_insight_runs.create(
            {
                id: data.id || undefined,
        
        run_type: data.run_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        period_start_at: data.period_start_at
        ||
        null
            ,
            
        period_end_at: data.period_end_at
        ||
        null
            ,
            
        prompt_snapshot: data.prompt_snapshot
        ||
        null
            ,
            
        output_summary: data.output_summary
        ||
        null
            ,
            
        consistency_score: data.consistency_score
        ||
        null
            ,
            
        completed_at: data.completed_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await ai_insight_runs.setTrading_account( data.trading_account || null, {
            transaction,
        });
        

        

        

        return ai_insight_runs;
    }
    

    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_insight_runsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                run_type: item.run_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                period_start_at: item.period_start_at
            ||
            null
            ,
            
                period_end_at: item.period_end_at
            ||
            null
            ,
            
                prompt_snapshot: item.prompt_snapshot
            ||
            null
            ,
            
                output_summary: item.output_summary
            ||
            null
            ,
            
                consistency_score: item.consistency_score
            ||
            null
            ,
            
                completed_at: item.completed_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return ai_insight_runs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.run_type !== undefined) updatePayload.run_type = data.run_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.period_start_at !== undefined) updatePayload.period_start_at = data.period_start_at;
        
        
        if (data.period_end_at !== undefined) updatePayload.period_end_at = data.period_end_at;
        
        
        if (data.prompt_snapshot !== undefined) updatePayload.prompt_snapshot = data.prompt_snapshot;
        
        
        if (data.output_summary !== undefined) updatePayload.output_summary = data.output_summary;
        
        
        if (data.consistency_score !== undefined) updatePayload.consistency_score = data.consistency_score;
        
        
        if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.trading_account !== undefined) {
            await ai_insight_runs.setTrading_account(
              
              data.trading_account,
              
              { transaction }
            );
        }
        

        
        

        

        return ai_insight_runs;
    }

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

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

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


        return ai_insight_runs;
    }

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

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

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

        await ai_insight_runs.destroy({
            transaction
        });

        return ai_insight_runs;
    }

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

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

        if (!ai_insight_runs) {
            return ai_insight_runs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.ai_insight_items_ai_insight_run = await ai_insight_runs.getAi_insight_items_ai_insight_run({
            transaction
        });
        
        
        
        
        
        
        
        output.trading_account = await ai_insight_runs.getTrading_account({
            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.trading_accounts,
        as: 'trading_account',
        
        where: filter.trading_account ? {
          [Op.or]: [
            { id: { [Op.in]: filter.trading_account.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.trading_account.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.prompt_snapshot) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_insight_runs',
                        'prompt_snapshot',
                        filter.prompt_snapshot,
                    ),
                };
            }
            
            if (filter.output_summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_insight_runs',
                        'output_summary',
                        filter.output_summary,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    period_start_at: {
                    ...where.period_start_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.period_end_atRange) {
                const [start, end] = filter.period_end_atRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    period_end_at: {
                    ...where.period_end_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.consistency_scoreRange) {
                const [start, end] = filter.consistency_scoreRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    consistency_score: {
                    ...where.consistency_score,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.completed_atRange) {
                const [start, end] = filter.completed_atRange;

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

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

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

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


      



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

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

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

    
};

