import { describe, expect, it } from "vitest";
import {
  formatAuditDateParts,
  formatAuditValue,
  parseAuditDetails,
  resolveAuditAction,
  resolveAuditActor,
  resolveAuditTarget,
} from "../../../../common/core/audit";

describe("common audit helpers", () => {
  it("parses audit details and falls back on invalid payloads", () => {
    expect(parseAuditDetails()).toEqual({});
    expect(parseAuditDetails("not-json")).toEqual({});
    expect(parseAuditDetails('{"action":"ADD_RELATION"}')).toEqual({
      action: "ADD_RELATION",
    });
  });

  it("formats audit values and dates", () => {
    const circular: Record<string, unknown> = {};
    circular.self = circular;

    expect(formatAuditValue(null)).toBe("-");
    expect(formatAuditValue("hello")).toBe("hello");
    expect(formatAuditValue({ a: 1 })).toBe('{"a":1}');
    expect(formatAuditValue(circular)).toBe("[object Object]");

    expect(formatAuditDateParts("")).toEqual({ date: "-", time: "-" });
    expect(formatAuditDateParts("invalid")).toEqual({
      date: "invalid",
      time: "-",
    });

    const parsed = formatAuditDateParts("2026-05-27T07:43:39.000Z");
    expect(parsed.date).toBe("2026-05-27");
    expect(parsed.time).not.toBe("-");
  });

  it("resolves audit actor, action, and target consistently", () => {
    expect(
      resolveAuditActor(
        { user_id: "actor-1" },
        { actor_id: "actor-2" },
      ),
    ).toBe("actor-1");
    expect(
      resolveAuditActor({ user_id: "" }, { actor_id: "actor-2" }),
    ).toBe("actor-2");
    expect(resolveAuditActor({ user_id: "" }, {})).toBe("-");

    expect(
      resolveAuditAction(
        { event_type: "UPDATE_CLIENT" },
        { action: "ADD_RELATION" },
      ),
    ).toBe("ADD_RELATION");
    expect(
      resolveAuditAction(
        { event_type: "UPDATE_CLIENT" },
        { method: "POST", path: "/dev/clients" },
      ),
    ).toBe("POST /dev/clients");
    expect(resolveAuditAction({ event_type: "UPDATE_CLIENT" }, {})).toBe(
      "UPDATE_CLIENT",
    );

    expect(resolveAuditTarget({ target: "target-1" })).toBe("target-1");
    expect(resolveAuditTarget({ target_id: "target-2" })).toBe("target-2");
    expect(resolveAuditTarget({})).toBe("-");
  });
});
