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

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

        const sandbox_scenarios = await db.sandbox_scenarios.create(
            {
                id: data.id || undefined,
        
        scenario_name: data.scenario_name
        ||
        null
            ,
            
        scenario_type: data.scenario_type
        ||
        null
            ,
            
        scenario_description: data.scenario_description
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        last_run_at: data.last_run_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await sandbox_scenarios.setCampaign_brain_config( data.campaign_brain_config || null, {
            transaction,
        });
        
        await sandbox_scenarios.setSafety_policy( data.safety_policy || null, {
            transaction,
        });
        

        

        

        return sandbox_scenarios;
    }
    

    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 sandbox_scenariosData = data.map((item, index) => ({
                id: item.id || undefined,
                
                scenario_name: item.scenario_name
            ||
            null
            ,
            
                scenario_type: item.scenario_type
            ||
            null
            ,
            
                scenario_description: item.scenario_description
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                last_run_at: item.last_run_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return sandbox_scenarios;
    }

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

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


        

        const updatePayload = {};
        
        if (data.scenario_name !== undefined) updatePayload.scenario_name = data.scenario_name;
        
        
        if (data.scenario_type !== undefined) updatePayload.scenario_type = data.scenario_type;
        
        
        if (data.scenario_description !== undefined) updatePayload.scenario_description = data.scenario_description;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.last_run_at !== undefined) updatePayload.last_run_at = data.last_run_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.campaign_brain_config !== undefined) {
            await sandbox_scenarios.setCampaign_brain_config(
              
              data.campaign_brain_config,
              
              { transaction }
            );
        }
        
        if (data.safety_policy !== undefined) {
            await sandbox_scenarios.setSafety_policy(
              
              data.safety_policy,
              
              { transaction }
            );
        }
        

        
        

        

        return sandbox_scenarios;
    }

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

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

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


        return sandbox_scenarios;
    }

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

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

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

        await sandbox_scenarios.destroy({
            transaction
        });

        return sandbox_scenarios;
    }

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

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

        if (!sandbox_scenarios) {
            return sandbox_scenarios;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.campaign_brain_config = await sandbox_scenarios.getCampaign_brain_config({
            transaction
        });
        
        
        output.safety_policy = await sandbox_scenarios.getSafety_policy({
            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.campaign_brain_configs,
        as: 'campaign_brain_config',
        
        where: filter.campaign_brain_config ? {
          [Op.or]: [
            { id: { [Op.in]: filter.campaign_brain_config.split('|').map(term => Utils.uuid(term)) } },
            {
              layer_name: {
                [Op.or]: filter.campaign_brain_config.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.scenario_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sandbox_scenarios',
                        'scenario_name',
                        filter.scenario_name,
                    ),
                };
            }
            
            if (filter.scenario_description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sandbox_scenarios',
                        'scenario_description',
                        filter.scenario_description,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.scenario_type) {
                where = {
                    ...where,
                scenario_type: filter.scenario_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.sandbox_scenarios.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(
                        'sandbox_scenarios',
                        'scenario_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

