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

import type { AdminAccessMatrixResponse, AdminAccessUsersResponse } from "../src/types/index.ts";
import { normalizeAccessDetail, normalizeAccessSummary, normalizeAccessUsers } from "../src/stores/admin-access-view.ts";
import { mergeProviderRow, normalizeProviderConfig, normalizeProviderProfiles, normalizeProviderValidation } from "../src/stores/provider-profiles-view.ts";

test("R4 Access helpers map runtime rows and OpenFGA summary", () => {
  const summary = normalizeAccessSummary({ contractVersion: "admin-access-v1", counts: { users: 3, tuples: 5, toolTuples: 4 }, openfga: { ready: true, status: "ready", storeName: "hwlab-v03" }, supported: { toolIds: ["hwpod", "github_pr"] } });
  assert.equal(summary.users, 3);
  assert.equal(summary.toolTuples, 4);
  assert.deepEqual(summary.toolIds, ["hwpod", "github_pr"]);
  assert.equal(summary.openfga.ready, true);

  const usersPayload = { users: [{ user: { id: "usr_1", username: "alice", role: "member", status: "active" }, tools: { hwpod: true, github_pr: false }, tupleCount: 1 }] } as unknown as AdminAccessUsersResponse;
  const users = normalizeAccessUsers(usersPayload);
  assert.equal(users.length, 1);
  assert.equal(users[0]?.id, "usr_1");
  assert.equal(users[0]?.toolCount, 1);
  assert.equal(users[0]?.tools.hwpod, true);
});

test("R4 Access detail maps tool object into toggles", () => {
  const detailPayload = { user: { id: "usr_1", username: "alice" }, tools: { hwpod: true, trans_cmd: false }, tuples: [{ userId: "usr_1", relation: "can_use", object: "tool:hwpod" }], openfga: { valuesRedacted: true } } as unknown as AdminAccessMatrixResponse;
  const detail = normalizeAccessDetail(detailPayload);
  assert.equal(detail.user?.id, "usr_1");
  assert.ok(detail.tools.some((tool) => tool.id === "hwpod" && tool.allowed));
  assert.ok(detail.tools.some((tool) => tool.id === "trans_cmd" && !tool.allowed));
  assert.equal(detail.tuples.length, 1);
});

test("R4 Provider helpers accept Sub2API-style item envelopes", () => {
  const rows = normalizeProviderProfiles({ data: { items: [{ profile: "deepseek", configured: true, secretRef: { namespace: "agentrun-v02", name: "agentrun-v02-provider-deepseek", keys: ["auth.json", "config.toml"] }, credentialHashSuffix: "abc123", configHashSuffix: "def456", bridge: { route: "Moon Bridge -> DeepSeek" }, valuesPrinted: false }] } });
  assert.equal(rows.length, 1);
  assert.equal(rows[0]?.profile, "deepseek");
  assert.equal(rows[0]?.secretRefText, "agentrun-v02/agentrun-v02-provider-deepseek [auth.json,config.toml]");
  assert.equal(rows[0]?.credentialHashSuffix, "abc123");
  assert.equal(rows[0]?.valuesPrinted, false);
});

test("R4 Provider config and validation summaries stay redacted", () => {
  const config = normalizeProviderConfig({ data: { profile: "deepseek", configToml: "model = \"deepseek-chat\"", configHashSuffix: "cfg123", valuesPrinted: false } }, "deepseek");
  assert.equal(config.profile, "deepseek");
  assert.match(config.configToml, /deepseek-chat/);
  assert.equal(config.valuesPrinted, false);

  const validation = normalizeProviderValidation({ data: { validationId: "val_1", profile: "deepseek", status: "completed", runId: "run_1", commandId: "cmd_1", result: { terminalStatus: "completed", agentRun: { jobName: "agentrun-v02-runner" } }, valuesPrinted: false } }, "deepseek");
  assert.equal(validation.validationId, "val_1");
  assert.equal(validation.jobName, "agentrun-v02-runner");
  assert.equal(validation.valuesPrinted, false);
});

test("R4 Provider merge keeps updated profile and ordering", () => {
  const rows = normalizeProviderProfiles({ items: [{ profile: "custom" }, { profile: "deepseek", configured: false }] });
  const updated = normalizeProviderProfiles({ items: [{ profile: "deepseek", configured: true, credentialHashSuffix: "abc" }] })[0] ?? null;
  const merged = mergeProviderRow(rows, updated);
  assert.equal(merged[0]?.profile, "deepseek");
  assert.equal(merged[0]?.configured, true);
  assert.equal(merged.length, 2);
});
