import Joi from 'joi'
import { BaseSvgScrapingService } from '../index.js'

const schema = Joi.object({
  message: Joi.alternatives()
    .try(Joi.string().regex(/^\d*$/), Joi.equal('unknown'))
    .required(),
}).required()

export default class SnykVulnerabilityBase extends BaseSvgScrapingService {
  static category = 'analysis'

  static defaultBadgeData = {
    label: 'vulnerabilities',
  }

  static render({ vulnerabilities }) {
    let color = 'red'
    if (vulnerabilities === '0') {
      color = 'brightgreen'
    }
    return {
      message: vulnerabilities,
      color,
    }
  }

  async fetch({ url, searchParams, errorMessages }) {
    const { message: vulnerabilities } = await this._requestSvg({
      url,
      schema,
      options: {
        searchParams,
      },
      errorMessages,
    })

    return { vulnerabilities }
  }
}
