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

import {
  AUDIT_FIELD_NAMES,
  PROTOCOL_AUDIT_FIELD_NAMES,
  assertAuditFields,
  createAuditRecord,
  createProtocolAuditEvent
} from "./index.mjs";

test("createAuditRecord exposes the L1 audit field names", () => {
  const record = createAuditRecord({
    requestId: "req_01J00000000000000000000000",
    actor: {
      type: "user",
      id: "usr_01J00000000000000000000000"
    },
    source: {
      serviceId: "hwlab-cloud-api",
      adapter: "json-rpc"
    },
    operation: "hardware.operation.request",
    target: {
      type: "project",
      id: "prj_01J00000000000000000000000"
    },
    result: "rejected",
    timestamp: "2026-05-21T00:00:00.000Z"
  });

  for (const field of AUDIT_FIELD_NAMES) {
    assert.ok(Object.hasOwn(record, field), `expected audit.${field}`);
  }

  assert.equal(record.requestId, "req_01J00000000000000000000000");
  assert.equal(record.actor.id, "usr_01J00000000000000000000000");
  assert.equal(record.source.serviceId, "hwlab-cloud-api");
  assert.equal(record.operation, "hardware.operation.request");
  assert.equal(record.target.type, "project");
  assert.equal(record.result, "rejected");
});

test("assertAuditFields rejects missing audit fields", () => {
  assert.throws(
    () =>
      assertAuditFields({
        requestId: "req_01J00000000000000000000000",
        actor: {},
        source: {},
        operation: "hardware.operation.request",
        target: {},
        result: "rejected"
      }),
    /audit.timestamp is required/
  );
});

test("createProtocolAuditEvent emits audit-event schema field names", () => {
  const event = createProtocolAuditEvent({
    auditId: "aud_01J00000000000000000000000",
    traceId: "trc_01J00000000000000000000000",
    actorType: "user",
    actorId: "usr_01J00000000000000000000000",
    action: "hardware.operation.request",
    targetType: "hardware_operation",
    targetId: "op_01J00000000000000000000000",
    projectId: "prj_01J00000000000000000000000",
    gatewaySessionId: "gws_01J00000000000000000000000",
    operationId: "op_01J00000000000000000000000",
    outcome: "accepted",
    occurredAt: "2026-05-21T00:00:00.000Z"
  });

  for (const field of PROTOCOL_AUDIT_FIELD_NAMES) {
    assert.ok(Object.hasOwn(event, field), `expected auditEvent.${field}`);
  }

  assert.equal(event.serviceId, "hwlab-cloud-api");
  assert.equal(event.environment, "dev");
  assert.equal(event.action, "hardware.operation.request");
});
