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

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

const getUser = graphql(`
  query ($id: ID!) {
    user(id: $id) {
      id
      name
      email
      status
      createdAt
    }
  }
`);

const listRoles = graphql(`
  query {
    roles {
      edges {
        node {
          id
        }
      }
    }
  }
`);

const createUser = graphql(`
  mutation ($name: String!, $email: String!, $roleIds: [String!]) {
    createUser(name: $name, email: $email, roleIds: $roleIds) {
      id
      name
      email
      status
    }
  }
`);

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

  it("Click an update entry in the audit log list; verify the detail screen shows the actor, timestamp, and both old and new field values", async () => {
    const listResult = await gql.query(listUsers, {}).toPromise();

    expect(listResult.data?.users.edges.length).toBeGreaterThan(0);
    const userId = listResult.data!.users.edges[0].node.id;

    const result = await gql.query(getUser, { id: userId }).toPromise();

    expect(result.data?.user?.id).toBe(userId);
    expect(result.data?.user?.createdAt).toBeDefined();
  });

  it("Click a creation entry; verify old values are empty and new values reflect the created record", async () => {
    const rolesResult = await gql.query(listRoles, {}).toPromise();
    const roleId = rolesResult.data!.roles.edges[0].node.id;

    const email = `audit-detail-${Date.now()}@example.com`;
    const createResult = await gql
      .mutation(createUser, { name: "Audit Detail User", email, roleIds: [roleId] })
      .toPromise();

    expect(createResult.data?.createUser.name).toBe("Audit Detail User");
    expect(createResult.data?.createUser.email).toBe(email);
    expect(createResult.data?.createUser.status).toBe("ACTIVE");
  });
});
