/******************************************************************************/
/* Copyright Yahoo Inc.
 *
 * SPDX-License-Identifier: Apache-2.0
 */
const Integration = require('../../integration.js');
const axios = require('axios');

class MalwareBazaarIntegration extends Integration {
  name = 'MalwareBazaar';
  icon = 'integrations/malwarebazaar/icon.png';
  order = 400;
  cacheTimeout = '1w';
  itypes = {
    hash: 'fetch'
  };

  homePage = 'https://bazaar.abuse.ch/';
  settings = {
    disabled: {
      help: 'Disable integration for all queries',
      type: 'boolean'
    }
  };

  card = {
    title: 'MalwareBazaar for %{query}',
    searchUrls: [{
      url: 'https://bazaar.abuse.ch/browse.php?search=md5%3A%{query}',
      itypes: ['hash'],
      name: 'Search MalwareBazaar for MD5: %{query}'
    }, {
      url: 'https://bazaar.abuse.ch/browse.php?search=sha256%3A%{query}',
      itypes: ['hash'],
      name: 'Search MalwareBazaar for SHA: %{query}'
    }],
    fields: []
  };

  constructor () {
    super();

    Integration.register(this);
  }

  async fetch (user, query) {
    try {
      const result = await axios.post('https://mb-api.abuse.ch/api/v1/', `query=get_info&hash=${query}`, {
        headers: {
          'User-Agent': this.userAgent()
        }
      });

      if (result.data.query_status.startsWith('no_result')) {
        return Integration.NoResult;
      }

      result.data._cont3xt = { count: 0 };
      if (result.data.query_status === 'ok' && result.data.data !== undefined) {
        result.data._cont3xt.count = result.data.data.length;
      }
      return result.data;
    } catch (err) {
      if (Integration.debug <= 1 && err?.response?.status === 404) { return null; }
      console.log(this.name, query, err);
      return null;
    }
  }
}

// eslint-disable-next-line no-new
new MalwareBazaarIntegration();
