import assert from "node:assert/strict";
import { test } from "bun:test";

import { applyCloudApiImageEnv, parsePort, parseTimeout } from "./runtime-options.ts";

test("parsePort preserves current hwlab-cloud-api port fallback behavior", () => {
  assert.equal(parsePort(undefined, 6667), 6667);
  assert.equal(parsePort("", 6667), 6667);
  assert.equal(parsePort("abc", 6667), 6667);
  assert.equal(parsePort("-1", 6667), 6667);
  assert.equal(parsePort("65536", 6667), 6667);
  assert.equal(parsePort("0", 6667), 0);
  assert.equal(parsePort("19667", 6667), 19667);
});

test("parseTimeout clamps parsed integer values to the configured range", () => {
  assert.equal(parseTimeout(undefined, 1200000, { min: 1000, max: 2400000 }), 1200000);
  assert.equal(parseTimeout("abc", 1200000, { min: 1000, max: 2400000 }), 1200000);
  assert.equal(parseTimeout("1", 1200000, { min: 1000, max: 2400000 }), 1000);
  assert.equal(parseTimeout("99999999", 1200000, { min: 1000, max: 2400000 }), 2400000);
  assert.equal(parseTimeout("1500", 1200000, { min: 1000, max: 2400000 }), 1500);
});

test("applyCloudApiImageEnv derives image identity from commit without overriding explicit values", () => {
  const env = { HWLAB_COMMIT_ID: "abcdef1234567890" };
  applyCloudApiImageEnv(env);
  assert.equal(env.HWLAB_IMAGE, "ghcr.io/pikastech/hwlab-cloud-api:abcdef1");
  assert.equal(env.HWLAB_IMAGE_TAG, "abcdef1");

  const explicit = {
    HWLAB_GIT_SHA: "11111112222222",
    HWLAB_IMAGE: "registry.local/custom:tag",
    HWLAB_IMAGE_TAG: "custom"
  };
  applyCloudApiImageEnv(explicit);
  assert.equal(explicit.HWLAB_IMAGE, "registry.local/custom:tag");
  assert.equal(explicit.HWLAB_IMAGE_TAG, "custom");
});
