import { type MockedFunction, beforeEach, describe, expect, test, vi } from "vitest";
import { UNKNOWN_DATA } from "../types/audit-log";
import { logAuditEvent } from "./service";

// Mocks
globalThis.console = { ...globalThis.console, error: vi.fn() };

vi.mock("../../../ee/license-check/lib/utils", () => ({
  getIsAuditLogsEnabled: vi.fn(),
}));
vi.mock("@formbricks/logger", () => ({
  logger: { audit: vi.fn(), error: vi.fn() },
}));

const validEvent = {
  actor: { id: "user-1", type: "user" as const },
  action: "created" as const,
  target: { id: "target-1", type: "user" as const },
  status: "success" as const,
  timestamp: new Date().toISOString(),
  organizationId: "org-1",
  ipAddress: "203.0.113.7",
  userAgent: "test-agent",
};

describe("logAuditEvent", () => {
  let getIsAuditLogsEnabled: MockedFunction<
    (typeof import("@/modules/ee/license-check/lib/utils"))["getIsAuditLogsEnabled"]
  >;
  let logger: (typeof import("@formbricks/logger"))["logger"];

  beforeEach(async () => {
    vi.clearAllMocks();
    getIsAuditLogsEnabled = vi.mocked(
      (await import("@/modules/ee/license-check/lib/utils")).getIsAuditLogsEnabled
    );
    logger = (await import("@formbricks/logger")).logger;
  });

  test("derives scalar actor and target search fields from the event", async () => {
    await logAuditEvent(validEvent);
    expect(logger.audit).toHaveBeenCalledWith({
      ...validEvent,
      actorId: "user-1",
      actorType: "user",
      targetId: "target-1",
      targetType: "user",
    });
  });

  test("logs event if access is granted and event is valid", async () => {
    getIsAuditLogsEnabled.mockResolvedValue(true);
    await logAuditEvent(validEvent);
    expect(logger.audit).toHaveBeenCalledWith(expect.objectContaining(validEvent));
    expect(logger.error).not.toHaveBeenCalled();
  });

  test("throws and logs error for invalid event", async () => {
    getIsAuditLogsEnabled.mockResolvedValue(true);
    const invalidEvent = { ...validEvent, action: "invalid.action" };
    await logAuditEvent(invalidEvent as Parameters<typeof logAuditEvent>[0]);
    expect(logger.audit).not.toHaveBeenCalled();
    expect(logger.error).toHaveBeenCalled();
  });

  test("handles UNKNOWN_DATA organizationId", async () => {
    getIsAuditLogsEnabled.mockResolvedValue(true);
    const event = { ...validEvent, organizationId: UNKNOWN_DATA };
    await logAuditEvent(event);
    expect(logger.audit).toHaveBeenCalledWith(expect.objectContaining(event));
  });

  test("does not throw if logger.audit throws", async () => {
    getIsAuditLogsEnabled.mockResolvedValue(true);
    vi.mocked(logger.audit).mockImplementation(() => {
      throw new Error("fail");
    });
    await logAuditEvent(validEvent);
    expect(logger.error).toHaveBeenCalled();
  });

  // `apiUrl` is validated with z.url(), and a validation failure is swallowed into a logger.error
  // rather than surfaced — so a producer passing a malformed value silently drops the whole audit
  // event. That is exactly how every MCP mutation went unaudited (ENG-2173).
  describe("apiUrl", () => {
    beforeEach(() => {
      getIsAuditLogsEnabled.mockResolvedValue(true);
    });

    test("drops the event when apiUrl is a bare path", async () => {
      await logAuditEvent({ ...validEvent, apiUrl: "/api/mcp" });
      expect(logger.audit).not.toHaveBeenCalled();
      expect(logger.error).toHaveBeenCalled();
    });

    test("logs the event when apiUrl is absolute", async () => {
      const event = { ...validEvent, apiUrl: "http://localhost:3000/api/mcp" };
      await logAuditEvent(event);
      expect(logger.audit).toHaveBeenCalledWith(expect.objectContaining(event));
      expect(logger.error).not.toHaveBeenCalled();
    });

    test("logs the event when apiUrl is omitted (optional, unlike a malformed one)", async () => {
      await logAuditEvent(validEvent);
      expect(logger.audit).toHaveBeenCalledWith(expect.objectContaining(validEvent));
      expect(logger.error).not.toHaveBeenCalled();
    });

    // Ties the MCP producer to this schema: the exact value the MCP tools pass must be one this
    // validator accepts, which is the invariant that broke.
    test("accepts the apiUrl the MCP tools actually pass", async () => {
      const { getMcpResourceUrl } = await import("@/modules/auth/lib/oauth-urls");
      await logAuditEvent({ ...validEvent, apiUrl: getMcpResourceUrl() });
      expect(logger.audit).toHaveBeenCalled();
      expect(logger.error).not.toHaveBeenCalled();
    });
  });
});
