import { it, expect } from 'vitest'
import { createPgliteClient } from './postgres/pglite.js'
import { healthCheck } from './health.js'
import type { Querier } from './index.js'

it('reports ok with a latency on a reachable db', async () => {
  const db = createPgliteClient()
  const res = await healthCheck(db).check()
  expect(res.name).toBe('db')
  expect(res.status).toBe('ok')
  expect(typeof res.latencyMs).toBe('number')
  expect(res.latencyMs).toBeGreaterThanOrEqual(0)
})

it('honours a custom name', async () => {
  const db = createPgliteClient()
  const res = await healthCheck(db, { name: 'primary' }).check()
  expect(res.name).toBe('primary')
})

it('NEVER throws on a failing query — returns status down', async () => {
  // a Querier whose execute rejects (dead connection)
  const dead = { execute: async () => { throw new Error('ECONNREFUSED') } } as unknown as Querier
  const res = await healthCheck(dead).check()
  expect(res.status).toBe('down')
})

it('SECURITY: a probe failure detail NEVER echoes the raw driver error', async () => {
  const secret = 'postgres://user:hunter2@db.internal:5432/prod'
  const leaky = { execute: async () => { throw new Error(secret) } } as unknown as Querier
  const res = await healthCheck(leaky).check()
  expect(res.status).toBe('down')
  expect(res.detail).toBe('query failed')
  expect(res.detail).not.toContain('hunter2')
  expect(res.detail).not.toContain('db.internal')
})
