import { describe, expect, it } from 'vitest'

import { AccessKeys, deriveAccessKeyCatalog, findAccessCatalogEntry, normalizeAccessKey } from '../access-keys'
import { accessTestOrganizationModel } from './access-test-fixtures'
import { scanAccessKeyUsages } from './access-key-scan'

const INTENTIONALLY_UNCONSUMED_ACCESS_KEYS = new Set([
  'secretsManage',
  'operationsManage',
  'acquisitionManage',
  'projectsManage',
  'clientsManage',
  'operationsRecentExecutions'
])

describe('access key coverage', () => {
  it('keeps every runtime consumer key present in the catalog', () => {
    const catalog = deriveAccessKeyCatalog(accessTestOrganizationModel)
    const usages = scanAccessKeyUsages()
    const consumerKeys = [
      ...usages.stringLiterals.map((usage) => ({ file: usage.file, key: normalizeAccessKey(usage.key) })),
      ...usages.accessKeySymbols.map((usage) => ({
        file: usage.file,
        key: AccessKeys[usage.symbol as keyof typeof AccessKeys]
      }))
    ]

    const missingCatalogEntries = consumerKeys
      .filter((usage) => findAccessCatalogEntry(catalog, usage.key) === undefined)
      .map((usage) => `${usage.file}: ${usage.key.systemPath}:${usage.key.action}`)

    expect(missingCatalogEntries).toEqual([])
  })

  it('keeps exported static AccessKeys either consumed or explicitly reserved', () => {
    const usages = scanAccessKeyUsages()
    const consumedSymbols = new Set(usages.accessKeySymbols.map((usage) => usage.symbol))
    const unconsumedSymbols = Object.keys(AccessKeys).filter((symbol) => !consumedSymbols.has(symbol))

    expect(unconsumedSymbols).toEqual([...INTENTIONALLY_UNCONSUMED_ACCESS_KEYS])
  })
})
