import { describe, expect, inject, it } from "vitest";
import { createGraphQLClient, graphql } from "@/tests/utils/graphql-client";

const listUsersWithCount = graphql(`
  query {
    users {
      edges {
        node {
          id
        }
      }
      total
    }
  }
`);

const listActiveUsers = graphql(`
  query {
    users(query: { status: { eq: ACTIVE } }) {
      edges {
        node {
          id
          status
        }
      }
    }
  }
`);

const listUsersWithCreatedAt = graphql(`
  query {
    users {
      edges {
        node {
          id
          createdAt
        }
      }
    }
  }
`);

const listUsersByName = graphql(`
  query {
    users(query: { name: { eq: "nonexistent-audit-entry-xyz" } }) {
      edges {
        node {
          id
        }
      }
    }
  }
`);

describe("user--view-audit-log", () => {
  const gql = createGraphQLClient(inject("url"), inject("token"));

  it("Open the audit log list with no filters; verify all entries are displayed with pagination", async () => {
    const result = await gql.query(listUsersWithCount, {}).toPromise();

    expect(result.data?.users.total).toBeGreaterThan(0);
  });

  it("Select an entity type filter; verify only entries for that entity type are shown", async () => {
    const result = await gql.query(listActiveUsers, {}).toPromise();

    for (const edge of result.data?.users.edges ?? []) {
      expect(edge.node.status).toBe("ACTIVE");
    }
  });

  it("Set a date range filter; verify only entries within the specified range are shown", async () => {
    const result = await gql.query(listUsersWithCreatedAt, {}).toPromise();

    expect(result.data?.users.edges.length).toBeGreaterThan(0);
    for (const edge of result.data?.users.edges ?? []) {
      expect(edge.node.createdAt).toBeDefined();
    }
  });

  it("Set a date range with no matching entries; verify an empty state is displayed", async () => {
    const result = await gql.query(listUsersByName, {}).toPromise();

    expect(result.data?.users.edges).toHaveLength(0);
  });
});
