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

const createRole = graphql(`
  mutation ($name: String!, $description: String, $permissions: [String!]!) {
    createRole(name: $name, description: $description, permissions: $permissions) {
      id
      name
      description
    }
  }
`);

const createRoleMinimal = graphql(`
  mutation ($name: String!, $permissions: [String!]!) {
    createRole(name: $name, permissions: $permissions) {
      id
    }
  }
`);

const listRolesByName = graphql(`
  query ($name: String!) {
    roles(query: { name: { eq: $name } }) {
      edges {
        node {
          id
          name
        }
      }
    }
  }
`);

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

  it("Submit the form with a unique name and selected permissions; verify the role appears in the role list", async () => {
    const roleName = `TestRole-${Date.now()}`;
    const result = await gql
      .mutation(createRole, {
        name: roleName,
        description: "A test role",
        permissions: ["user-management:user:createUser", "user-management:user:updateUser"],
      })
      .toPromise();

    expect(result.data?.createRole.name).toBe(roleName);

    const listResult = await gql.query(listRolesByName, { name: roleName }).toPromise();

    expect(listResult.data?.roles.edges).toHaveLength(1);
  });

  it("Submit the form with a name already used by an existing role; verify an error is shown and no role is created", async () => {
    const roleName = `DupRole-${Date.now()}`;
    await gql.mutation(createRoleMinimal, { name: roleName, permissions: [] }).toPromise();

    await expect(
      gql.mutation(createRoleMinimal, { name: roleName, permissions: [] }).toPromise(),
    ).rejects.toThrow();
  });

  it("Submit the form with the name field empty; verify a validation error is shown and submission is blocked", async () => {
    await expect(
      gql.mutation(createRoleMinimal, { name: "", permissions: [] }).toPromise(),
    ).rejects.toThrow();
  });
});
