// Integration test for the Fastify skeleton (Task 1 of
// docs/superpowers/plans/2026-07-31-local-app.md). Boots the app builder
// directly (fastify.inject — no real port) against a throwaway DB created
// by the existing test-db helper, connecting as the `app` role.

import { describe, it, expect } from "vitest";
import { createTestDb } from "../helpers/db.js";
// Where the database is, resolved once for the whole run: your ADMIN_URL /
// DATABASE_URL if you set one, otherwise the PostgreSQL Balanced Sum installed on
// this machine. Every file in this directory used to carry its own copy of that
// decision, hardcoded to the Docker container that no longer exists.
import { dbUrl } from "../helpers/test-db-admin.js";
import { buildApp } from "../../server/src/app.js";

describe("GET /api/health", () => {
  // This test provisions its database inside the test body, so it gets the
  // same 60s budget the rest of the suite gives its beforeAll provisioning
  // rather than vitest's 5s default. See tests/server/companies.test.ts.
  it("reports the DB reachable, via the app role, against a throwaway database", async () => {
    const db = await createTestDb();
    const app = await buildApp({ databaseUrl: await dbUrl(db.dbName, "app", "app") });
    try {
      const res = await app.inject({ method: "GET", url: "/api/health" });
      expect(res.statusCode).toBe(200);
      const body = res.json() as { ok: boolean; db: boolean; migrations: string | null };
      expect(body.ok).toBe(true);
      expect(body.db).toBe(true);
      // The `app` role is not granted SELECT on schema_migrations (see
      // db/migrations) — the health check falls back to `SELECT 1` and
      // reports migrations as null rather than failing.
      expect(body.migrations).toBeNull();
    } finally {
      await app.close();
      await db.close();
    }
  }, 60_000);

  it("reports db unreachable when the connection is bad", async () => {
    const app = await buildApp({
      databaseUrl: "postgres://app:app@127.0.0.1:1/nonexistent",
    });
    try {
      const res = await app.inject({ method: "GET", url: "/api/health" });
      expect(res.statusCode).toBe(200);
      const body = res.json() as { ok: boolean; db: boolean; migrations: string | null };
      expect(body.ok).toBe(false);
      expect(body.db).toBe(false);
      expect(body.migrations).toBeNull();
    } finally {
      await app.close();
    }
  });
});
