import { describe, expect, it } from "vitest";
import {
  isAuditActionStatisticsData,
  isAuditLogPage,
  isAuditTrendData,
  isAuditUserStatisticsData,
} from "../auditTypes";

const baseLog = {
  id: "1",
  username: null,
  realName: null,
  organizationName: null,
  actionType: "LOGIN",
  targetType: null,
  targetId: null,
  targetName: null,
  operationResult: "FAILURE",
  failureReason: "凭据无效",
  clientIp: null,
  requestId: null,
  createdAt: "2026-07-23T03:00:00.000Z",
};
const page = {
  items: [baseLog],
  page: 1,
  pageSize: 20,
  total: 1,
  totalPages: 1,
};

describe("F7 audit DTO guards", () => {
  it("接受正式可空字段并保持字符串ID", () => {
    expect(isAuditLogPage(page)).toBe(true);
    expect(typeof page.items[0].id).toBe("string");
  });

  it.each([
    { ...baseLog, id: 1 },
    { ...baseLog, createdAt: "2026-07-23 03:00:00" },
    { ...baseLog, actionType: "UNKNOWN_ACTION" },
    { ...baseLog, operationResult: "OK" },
    { ...baseLog, targetType: "DOCUMENT_FILE" },
    { ...baseLog, created_at: baseLog.createdAt },
    { ...baseLog, unexpected: true },
  ])("拒绝number ID、非UTC、未知枚举、snake_case和未知字段", (item) => {
    expect(isAuditLogPage({ ...page, items: [item] })).toBe(false);
  });

  it("严格校验分页结构", () => {
    expect(isAuditLogPage({ ...page, page: 0 })).toBe(false);
    expect(isAuditLogPage({ ...page, pageSize: 101 })).toBe(false);
    expect(isAuditLogPage({ ...page, extra: 1 })).toBe(false);
  });

  it("严格校验趋势、动作和活跃用户响应", () => {
    expect(
      isAuditTrendData({
        items: [{ period: "2026-07-21", operationCount: 0 }],
      }),
    ).toBe(true);
    expect(
      isAuditActionStatisticsData({
        items: [{ actionType: "LOGIN", count: 1 }],
      }),
    ).toBe(true);
    expect(
      isAuditActionStatisticsData({
        items: [{ actionType: "RESTORE_DOCUMENT", count: 1 }],
      }),
    ).toBe(true);
    expect(
      isAuditUserStatisticsData({
        items: [
          {
            userId: "2",
            realName: null,
            organizationName: null,
            operationCount: 1,
          },
        ],
      }),
    ).toBe(true);
    expect(
      isAuditUserStatisticsData({
        items: [
          {
            userId: 2,
            realName: null,
            organizationName: null,
            operationCount: 1,
          },
        ],
      }),
    ).toBe(false);
    expect(
      isAuditActionStatisticsData({
        items: [{ actionType: "EXPORT_AUDIT", count: 1 }],
      }),
    ).toBe(false);
  });

  it("审计日志严格接受RESTORE_DOCUMENT且仍拒绝未知动作", () => {
    expect(isAuditLogPage({
      ...page,
      items: [{ ...baseLog, actionType: "RESTORE_DOCUMENT" }],
    })).toBe(true);
    expect(isAuditLogPage({
      ...page,
      items: [{ ...baseLog, actionType: "RESTORE_ANYTHING" }],
    })).toBe(false);
  });
});
