import assert from "node:assert/strict";
import test from "node:test";

import { resolveDeviceDatabaseUrl } from "../src/database-config.mjs";

test("builds the database URL from a file-backed password", async () => {
  const password = "test-only-database-password-with-32-bytes";
  const url = await resolveDeviceDatabaseUrl(
    {
      DEVICE_DATABASE_HOST: "device-postgres",
      DEVICE_DATABASE_PORT: "5432",
      DEVICE_DATABASE_NAME: "device_plane",
      DEVICE_DATABASE_USER: "device_plane",
      DEVICE_DATABASE_PASSWORD_FILE: "/run/test/postgres-password",
    },
    async (path, encoding) => {
      assert.equal(path, "/run/test/postgres-password");
      assert.equal(encoding, "utf8");
      return `${password}\n`;
    },
  );

  assert.equal(
    url,
    `postgresql://device_plane:${encodeURIComponent(password)}@device-postgres:5432/device_plane?sslmode=disable`,
  );
});

test("rejects a short file-backed database password", async () => {
  await assert.rejects(
    resolveDeviceDatabaseUrl(
      {
        DEVICE_DATABASE_HOST: "device-postgres",
        DEVICE_DATABASE_NAME: "device_plane",
        DEVICE_DATABASE_USER: "device_plane",
        DEVICE_DATABASE_PASSWORD_FILE: "/run/test/postgres-password",
      },
      async () => "too-short",
    ),
    /device_database_password_invalid/,
  );
});

test("keeps an explicit database URL as a compatibility-only boundary", async () => {
  const explicit = "postgresql://local:test@127.0.0.1:5432/device_plane";
  assert.equal(
    await resolveDeviceDatabaseUrl({ DEVICE_DATABASE_URL: explicit }),
    explicit,
  );
});
