import { describe, it, expect } from 'vitest'
import { onAuditEvent, type Alerter, type AlertKind } from '../src/audit/alert.js'
import { buildAuditEvent } from '../src/audit/log.js'
import { principal } from './_helpers.js'

const NOW = 1_700_000_000

function fakeAlerter() {
  const fired: { kind: AlertKind }[] = []
  const alerter: Alerter = { fire: async (kind) => void fired.push({ kind }) }
  return { alerter, fired }
}

describe('audit-alert wiring (T14)', () => {
  it('fires a cross-tenant alert on a cross-tenant-attempt event', async () => {
    const { alerter, fired } = fakeAlerter()
    const e = buildAuditEvent({
      action: 'cross-tenant-attempt',
      principal: null,
      hostId: 'host-B',
      sessionId: null,
      jti: null,
      outcome: 'deny',
      reason: 'cross_tenant',
      remoteAddrHash: 'h',
      now: NOW,
    })
    await onAuditEvent(e, alerter)
    expect(fired).toEqual([{ kind: 'cross-tenant' }])
  })

  it('does NOT alert on an ordinary attach allow', async () => {
    const { alerter, fired } = fakeAlerter()
    const e = buildAuditEvent({
      action: 'attach',
      principal: principal('acct-A'),
      hostId: 'host-A',
      sessionId: null,
      jti: 'j',
      outcome: 'allow',
      reason: 'ok',
      remoteAddrHash: 'h',
      now: NOW,
    })
    await onAuditEvent(e, alerter)
    expect(fired).toHaveLength(0)
  })
})
