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

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

        const threat_indicators = await db.threat_indicators.create(
            {
                id: data.id || undefined,
        
        indicator_value: data.indicator_value
        ||
        null
            ,
            
        indicator_type: data.indicator_type
        ||
        null
            ,
            
        confidence: data.confidence
        ||
        null
            ,
            
        severity: data.severity
        ||
        null
            ,
            
        first_seen_at: data.first_seen_at
        ||
        null
            ,
            
        last_seen_at: data.last_seen_at
        ||
        null
            ,
            
        source: data.source
        ||
        null
            ,
            
        context: data.context
        ||
        null
            ,
            
        active: data.active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await threat_indicators.setThreat_actor( data.threat_actor || null, {
            transaction,
        });
        
        await threat_indicators.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return threat_indicators;
    }
    

    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 threat_indicatorsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                indicator_value: item.indicator_value
            ||
            null
            ,
            
                indicator_type: item.indicator_type
            ||
            null
            ,
            
                confidence: item.confidence
            ||
            null
            ,
            
                severity: item.severity
            ||
            null
            ,
            
                first_seen_at: item.first_seen_at
            ||
            null
            ,
            
                last_seen_at: item.last_seen_at
            ||
            null
            ,
            
                source: item.source
            ||
            null
            ,
            
                context: item.context
            ||
            null
            ,
            
                active: item.active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return threat_indicators;
    }

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

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


        

        const updatePayload = {};
        
        if (data.indicator_value !== undefined) updatePayload.indicator_value = data.indicator_value;
        
        
        if (data.indicator_type !== undefined) updatePayload.indicator_type = data.indicator_type;
        
        
        if (data.confidence !== undefined) updatePayload.confidence = data.confidence;
        
        
        if (data.severity !== undefined) updatePayload.severity = data.severity;
        
        
        if (data.first_seen_at !== undefined) updatePayload.first_seen_at = data.first_seen_at;
        
        
        if (data.last_seen_at !== undefined) updatePayload.last_seen_at = data.last_seen_at;
        
        
        if (data.source !== undefined) updatePayload.source = data.source;
        
        
        if (data.context !== undefined) updatePayload.context = data.context;
        
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.threat_actor !== undefined) {
            await threat_indicators.setThreat_actor(
              
              data.threat_actor,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await threat_indicators.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return threat_indicators;
    }

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

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

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


        return threat_indicators;
    }

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

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

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

        await threat_indicators.destroy({
            transaction
        });

        return threat_indicators;
    }

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

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

        if (!threat_indicators) {
            return threat_indicators;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.attack_map_events_indicator = await threat_indicators.getAttack_map_events_indicator({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.threat_actor = await threat_indicators.getThreat_actor({
            transaction
        });
        
        
        output.organizations = await threat_indicators.getOrganizations({
            transaction
        });
        
        

        return output;
    }

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

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.indicator_value) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'threat_indicators',
                        'indicator_value',
                        filter.indicator_value,
                    ),
                };
            }
            
            if (filter.source) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'threat_indicators',
                        'source',
                        filter.source,
                    ),
                };
            }
            
            if (filter.context) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'threat_indicators',
                        'context',
                        filter.context,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.indicator_type) {
                where = {
                    ...where,
                indicator_type: filter.indicator_type,
            };
            }
            
            if (filter.confidence) {
                where = {
                    ...where,
                confidence: filter.confidence,
            };
            }
            
            if (filter.severity) {
                where = {
                    ...where,
                severity: filter.severity,
            };
            }
            
            if (filter.active) {
                where = {
                    ...where,
                active: filter.active,
            };
            }
            


      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



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

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.threat_indicators.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

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

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

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

    
};

