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

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

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

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

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

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

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

  // Create our own active role so this file does not depend on seeded roles.
  // Other tests deactivate roles in parallel, so reusing one from the list is unsafe.
  let activeRoleId: string;
  beforeAll(async () => {
    const res = await gql
      .mutation(createActiveRole, { name: `update-profile-active-${Date.now()}`, permissions: [] })
      .toPromise();
    activeRoleId = res.data!.createRole.id;
  });

  it("Change a user's name and submit; verify the updated name is reflected on the detail page", async () => {
    const email = `update-name-${Date.now()}@example.com`;

    const createResult = await gql
      .mutation(createUserIdOnly, {
        name: "Before Update",
        email,
        roleIds: [activeRoleId],
      })
      .toPromise();

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

    expect(res.data?.updateUserProfile.name).toBe("After Update");
  });

  it("Change a user's email to a valid unique address and submit; verify the updated email is shown", async () => {
    const ts = Date.now();

    const createResult = await gql
      .mutation(createUserIdOnly, {
        name: "Email Update User",
        email: `old-email-${ts}@example.com`,
        roleIds: [activeRoleId],
      })
      .toPromise();

    const newEmail = `new-email-${ts}@example.com`;
    const res = await gql
      .mutation(updateUserProfileEmail, {
        userId: createResult.data!.createUser.id,
        name: "Email Update User",
        email: newEmail,
      })
      .toPromise();

    expect(res.data?.updateUserProfile.email).toBe(newEmail);
  });

  it("Change a user's email to one already assigned to another user; verify an error is shown and no change is saved", async () => {
    const ts = Date.now();

    await gql
      .mutation(createUserIdOnly, {
        name: "User A",
        email: `dup-a-${ts}@example.com`,
        roleIds: [activeRoleId],
      })
      .toPromise();

    const createB = await gql
      .mutation(createUserIdOnly, {
        name: "User B",
        email: `dup-b-${ts}@example.com`,
        roleIds: [activeRoleId],
      })
      .toPromise();

    await expect(
      gql
        .mutation(updateUserProfileIdOnly, {
          userId: createB.data!.createUser.id,
          name: "User B",
          email: `dup-a-${ts}@example.com`,
        })
        .toPromise(),
    ).rejects.toThrow();
  });

  it("Clear the name field and submit; verify a validation error is shown", async () => {
    const email = `clear-name-${Date.now()}@example.com`;

    const createResult = await gql
      .mutation(createUserIdOnly, {
        name: "Clear Name User",
        email,
        roleIds: [activeRoleId],
      })
      .toPromise();

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