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

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

        const campaign_brain_configs = await db.campaign_brain_configs.create(
            {
                id: data.id || undefined,
        
        layer_name: data.layer_name
        ||
        null
            ,
            
        priority_order: data.priority_order
        ||
        null
            ,
            
        is_enabled: data.is_enabled
        ||
        false
        
            ,
            
        influence_weight: data.influence_weight
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await campaign_brain_configs.setCampaign( data.campaign || null, {
            transaction,
        });
        
        await campaign_brain_configs.setBrain_profile( data.brain_profile || null, {
            transaction,
        });
        

        
        await campaign_brain_configs.setEnabled_skill_modules(data.enabled_skill_modules || [], {
            transaction,
        });
        

        

        return campaign_brain_configs;
    }
    

    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 campaign_brain_configsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                layer_name: item.layer_name
            ||
            null
            ,
            
                priority_order: item.priority_order
            ||
            null
            ,
            
                is_enabled: item.is_enabled
            ||
            false
        
            ,
            
                influence_weight: item.influence_weight
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return campaign_brain_configs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.layer_name !== undefined) updatePayload.layer_name = data.layer_name;
        
        
        if (data.priority_order !== undefined) updatePayload.priority_order = data.priority_order;
        
        
        if (data.is_enabled !== undefined) updatePayload.is_enabled = data.is_enabled;
        
        
        if (data.influence_weight !== undefined) updatePayload.influence_weight = data.influence_weight;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.campaign !== undefined) {
            await campaign_brain_configs.setCampaign(
              
              data.campaign,
              
              { transaction }
            );
        }
        
        if (data.brain_profile !== undefined) {
            await campaign_brain_configs.setBrain_profile(
              
              data.brain_profile,
              
              { transaction }
            );
        }
        

        
        
        if (data.enabled_skill_modules !== undefined) {
            await campaign_brain_configs.setEnabled_skill_modules(data.enabled_skill_modules, { transaction });
        }
        

        

        return campaign_brain_configs;
    }

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

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

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


        return campaign_brain_configs;
    }

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

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

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

        await campaign_brain_configs.destroy({
            transaction
        });

        return campaign_brain_configs;
    }

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

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

        if (!campaign_brain_configs) {
            return campaign_brain_configs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.sandbox_scenarios_campaign_brain_config = await campaign_brain_configs.getSandbox_scenarios_campaign_brain_config({
            transaction
        });
        
        
        
        
        
        output.campaign = await campaign_brain_configs.getCampaign({
            transaction
        });
        
        
        output.brain_profile = await campaign_brain_configs.getBrain_profile({
            transaction
        });
        
        
        output.enabled_skill_modules = await campaign_brain_configs.getEnabled_skill_modules({
            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.campaigns,
        as: 'campaign',
        
        where: filter.campaign ? {
          [Op.or]: [
            { id: { [Op.in]: filter.campaign.split('|').map(term => Utils.uuid(term)) } },
            {
              campaign_name: {
                [Op.or]: filter.campaign.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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


      {
        model: db.skill_modules,
        as: 'enabled_skill_modules',
        required: false,
      },


    ];

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

            
            if (filter.layer_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'campaign_brain_configs',
                        'layer_name',
                        filter.layer_name,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      

      


      if (filter.enabled_skill_modules) {
        const searchTerms = filter.enabled_skill_modules.split('|');

        include = [
          {
            model: db.skill_modules,
            as: 'enabled_skill_modules_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  module_name: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


            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.campaign_brain_configs.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(
                        'campaign_brain_configs',
                        'layer_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

