import { sql } from 'drizzle-orm'
import type { HealthCheck, HealthResult } from '@platform-modules/util/health'
import type { Querier, Schema } from './index.js'

export interface DbHealthOptions {
  /** Name surfaced in the `HealthResult` (default `'db'`). */
  name?: string
}

/**
 * A `SELECT 1` round-trip probe over any query-capable handle.
 *
 * Returns a `HealthCheck` whose `check()` NEVER throws — a failed query becomes
 * `status:'down'` with a GENERIC `detail`. The raw driver error is deliberately
 * swallowed: it can carry a DSN, credentials, or host topology and must never
 * reach an admin screen or log (info-disclosure hard floor).
 */
export function healthCheck<S extends Schema = Record<string, never>>(
  db: Querier<S>,
  opts?: DbHealthOptions,
): HealthCheck {
  const name = opts?.name ?? 'db'
  return {
    name,
    async check(): Promise<HealthResult> {
      const start = Date.now()
      try {
        await db.execute(sql`SELECT 1`)
        return { name, status: 'ok', latencyMs: Date.now() - start }
      } catch {
        return { name, status: 'down', detail: 'query failed', latencyMs: Date.now() - start }
      }
    },
  }
}
