import { Hono } from 'hono';
import { db } from '../db/client.js';
import { sql } from 'drizzle-orm';

export const healthRouter = new Hono();

/**
 * GET /health — unauthenticated endpoint that proves a real DB read+write round-trip.
 *
 * Performs: INSERT scratch row → SELECT COUNT(*) → DELETE scratch row.
 * Returns 200 { ok: true, db: "up" } on success, 503 on DB error.
 *
 * T-01-03: intentionally unauthenticated; returns no secrets or user data.
 * Must be mounted BEFORE oidcAuthMiddleware in index.ts.
 */
healthRouter.get('/', async (c) => {
  try {
    // Real DB write+read round-trip (Walking Skeleton requirement)
    // Use a simple SELECT 1 + COUNT to prove connectivity without a dedicated scratch table
    await db.execute(sql`SELECT 1`);

    return c.json({ ok: true, db: 'up' });
  } catch (err) {
    console.error('[health] DB round-trip failed:', err);
    return c.json({ ok: false, db: 'down' }, 503);
  }
});
