import { NotFound } from '../index.js'
import SynkVulnerabilityBase from './snyk-vulnerability-base.js'

export default class SnykVulnerabilityNpm extends SynkVulnerabilityBase {
  static route = {
    base: 'snyk/vulnerabilities/npm',
    pattern: ':packageName(.+?)',
  }

  static examples = [
    {
      title: 'Snyk Vulnerabilities for npm package',
      pattern: ':packageName',
      namedParams: {
        packageName: 'mocha',
      },
      staticPreview: this.render({ vulnerabilities: '0' }),
    },
    {
      title: 'Snyk Vulnerabilities for npm package version',
      pattern: ':packageName',
      namedParams: {
        packageName: 'mocha@4.0.0',
      },
      staticPreview: this.render({ vulnerabilities: '1' }),
    },
    {
      title: 'Snyk Vulnerabilities for npm scoped package',
      pattern: ':packageName',
      namedParams: {
        packageName: '@babel/core',
      },
      staticPreview: this.render({ vulnerabilities: '0' }),
    },
  ]

  async handle({ packageName }) {
    const url = `https://snyk.io/test/npm/${packageName}/badge.svg`

    try {
      const { vulnerabilities } = await this.fetch({
        url,
        // Snyk returns an HTTP 200 with an HTML page when the specified
        // npm package is not found that contains the text 404.
        // Including this in case Snyk starts returning a 404 response code instead.
        errorMessages: {
          404: 'npm package is invalid or does not exist',
        },
      })
      return this.constructor.render({ vulnerabilities })
    } catch (e) {
      // If the package is invalid/nonexistent Snyk will return an HTML page
      // which will result in an InvalidResponse error being thrown by the valueFromSvgBadge()
      // function. Catching it here to switch to a more contextualized error message.
      throw new NotFound({
        prettyMessage: 'npm package is invalid or does not exist',
      })
    }
  }
}
