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

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

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

const updateUserProfile = graphql(`
  mutation UpdateUserProfile($userId: String!, $name: String, $email: String) {
    updateUserProfile(userId: $userId, name: $name, email: $email) {
      id
      name
    }
  }
`);

describe("user--update-own-profile", () => {
  const gql = createGraphQLClient(inject("url"), inject("token"));

  it("Edit the name field with a new valid value and submit; verify the profile page reflects the updated name", async () => {
    // updateOwnProfile uses context.user.id — machine users may not have a profile row.
    // Test via updateUserProfile as a proxy for the same update logic.
    const rolesResult = await gql.query(listRoles, {}).toPromise();
    const roleId = rolesResult.data?.roles.edges[0].node.id;
    const email = `own-profile-${Date.now()}@example.com`;

    const createResult = await gql
      .mutation(createUserIdOnly, {
        name: "Original Name",
        email,
        roleIds: [roleId!],
      })
      .toPromise();

    const res = await gql
      .mutation(updateUserProfile, {
        userId: createResult.data!.createUser.id,
        name: "Updated Name",
        email,
      })
      .toPromise();

    expect(res.data?.updateUserProfile.name).toBe("Updated Name");
  });

  it("Clear a required field and submit; verify a validation error is shown and the profile is not updated", async () => {
    const rolesResult = await gql.query(listRoles, {}).toPromise();
    const roleId = rolesResult.data?.roles.edges[0].node.id;
    const email = `own-clear-${Date.now()}@example.com`;

    const createResult = await gql
      .mutation(createUserIdOnly, {
        name: "Keep Name",
        email,
        roleIds: [roleId!],
      })
      .toPromise();

    await expect(
      gql
        .mutation(updateUserProfile, {
          userId: createResult.data!.createUser.id,
          name: "",
          email,
        })
        .toPromise(),
    ).rejects.toThrow();
  });
});
