import { fileURLToPath } from "node:url";
import { afterAll, describe, expect, it } from "vitest";
import { createPostgresRuntime, type PostgresRuntime } from "@awp/persistence";

const requiredEnvironment = (name: string): string => {
  const value = process.env[name]?.trim();
  if (!value) throw new Error(`${name} is required for the live AC-02 proof`);
  return value;
};

const suite = process.env.AWP_GOLIVE_EXECUTION === "1" ? describe : describe.skip;
const migrationsFolder = fileURLToPath(
  new URL("../../packages/persistence/drizzle/", import.meta.url),
);

async function body(response: Response): Promise<Record<string, unknown>> {
  return (await response.json()) as Record<string, unknown>;
}

suite("AC-02 deployed control-plane PostgreSQL health", () => {
  let runtime: PostgresRuntime | undefined;

  afterAll(async () => {
    await runtime?.close();
  });

  it("serves the configured deployed web and control-plane health endpoints", async () => {
    const controlPlaneUrl = requiredEnvironment("AWP_CONTROL_PLANE_URL").replace(/\/$/u, "");
    const webUrl = requiredEnvironment("AWP_WEB_URL").replace(/\/$/u, "");
    const [webResponse, healthResponse] = await Promise.all([
      fetch(webUrl),
      fetch(`${controlPlaneUrl}/health`),
    ]);

    expect(webResponse.ok).toBe(true);
    expect(healthResponse.status).toBe(200);
    expect(await body(healthResponse)).toMatchObject({
      status: "ok",
      database: "postgresql",
      migrations: { pending: 0, drift: [] },
    });
  });

  it("proves every repository migration is applied with no pending migration or drift", async () => {
    const databaseUrl = requiredEnvironment("AWP_TEST_POSTGRES_URL");
    runtime = createPostgresRuntime(databaseUrl, migrationsFolder);
    const status = await runtime.migrationStatus();

    expect(status.expected).toBeGreaterThan(0);
    expect(status.applied).toBe(status.expected);
    expect(status.pending).toBe(0);
    expect(status.drift).toEqual([]);
  });
});
