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

const listUsers = graphql(`
  query {
    users {
      edges {
        node {
          id
          name
          email
          status
        }
      }
    }
  }
`);

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

const listUsersByNamePrefix = graphql(`
  query {
    users(query: { name: { hasPrefix: "Admin" } }) {
      edges {
        node {
          id
          name
        }
      }
    }
  }
`);

const listUsersByExactName = graphql(`
  query {
    users(query: { name: { eq: "nonexistent-user-xyz-12345" } }) {
      edges {
        node {
          id
        }
      }
    }
  }
`);

describe("user--browse-user-list", () => {
  const gql = createGraphQLClient(inject("url"), inject("token"));

  it("Open the user list page; verify all users are displayed with name, email, role, and status", async () => {
    const result = await gql.query(listUsers, {}).toPromise();

    expect(result.data?.users.edges.length).toBeGreaterThan(0);
    const user = result.data?.users.edges[0].node;
    expect(user?.name).toBeDefined();
    expect(user?.email).toBeDefined();
    expect(user?.status).toBeDefined();
  });

  it("Filter by INACTIVE status; verify only inactive users are shown", async () => {
    const result = await gql.query(listInactiveUsers, {}).toPromise();

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

  it("Search by a partial name; verify matching users are displayed", async () => {
    const result = await gql.query(listUsersByNamePrefix, {}).toPromise();

    for (const edge of result.data?.users.edges ?? []) {
      expect(edge.node.name).toContain("Admin");
    }
  });

  it("Apply a filter that matches no users; verify an empty state message is shown", async () => {
    const result = await gql.query(listUsersByExactName, {}).toPromise();

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