const chai = require('chai')
const expect = chai.expect

const getConstants = require('../../../src/constants').getConstants

// #789 - don't allow lowercase CVE
describe('CVE IDs should be well formed', () => {
  context('Negative tests', () => {
    it('should not match lowercase', () => {
      expect('cve-2022-1234567890').to.not.match(getConstants().CVE_ID_REGEX)
    })
    it('should not match invalid prefix', () => {
      expect('abc-2022-1234567890').to.not.match(getConstants().CVE_ID_REGEX)
    })
    it('should not match non-digit year', () => {
      expect('CVE-abcd-1234567890').to.not.match(getConstants().CVE_ID_REGEX)
    })
    it('should not match non-digit ID', () => {
      expect('CVE-2022-abcdefghij').to.not.match(getConstants().CVE_ID_REGEX)
    })
    it("should not match years that aren't exactly 4 digits", () => {
      expect('CVE-22-1234567890').to.not.match(getConstants().CVE_ID_REGEX)
      expect('CVE-20222-1234567890').to.not.match(getConstants().CVE_ID_REGEX)
    })
    it("should not match IDs that aren't 4-19 digits", () => {
      expect('CVE-2022-123').to.not.match(getConstants().CVE_ID_REGEX)
      expect('CVE-2022-12345678901234567890').to.not.match(getConstants().CVE_ID_REGEX)
    })
    it('should not match without dashes', () => {
      expect('CVE20221234567890').to.not.match(getConstants().CVE_ID_REGEX)
    })
  })

  context('Positive tests', () => {
    it('should match uppercase', () => {
      expect('CVE-2022-1234567890').to.match(getConstants().CVE_ID_REGEX)
    })
    it('should match IDs that are 4-19 digits', () => {
      const cveId = 'CVE-2022-'

      // build strings for the ID part
      for (let i = 4; i < 20; i++) {
        // pad the end with a random number up to i
        const fullId = cveId.padEnd(cveId.length + i, Math.floor(Math.random() * 9))
        expect(fullId).to.match(getConstants().CVE_ID_REGEX, `Failed with ${fullId}`)
      }
    })
  })
})
