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

const createAttributeFull = graphql(`
  mutation CreateAttributeFull($code: String!, $name: String!, $valueLabels: [String!]) {
    createAttribute(code: $code, name: $name, valueLabels: $valueLabels) {
      id
      code
      name
    }
  }
`);

const createAttributeIdOnly = graphql(`
  mutation CreateAttributeIdOnly($code: String!, $name: String!, $valueLabels: [String!]) {
    createAttribute(code: $code, name: $name, valueLabels: $valueLabels) {
      id
    }
  }
`);

describe("product-manager--create-attribute", () => {
  const gql = createGraphQLClient(inject("url"), inject("token"));

  it("Given valid inputs, when the form is submitted, then an attribute is created with the given code and name.", async () => {
    const code = `ATTR-${Date.now()}`;
    const res = await gql
      .mutation(createAttributeFull, {
        code,
        name: "Test Attribute",
        valueLabels: ["Value A", "Value B"],
      })
      .toPromise();

    expect(res.data?.createAttribute.code).toBe(code);
    expect(res.data?.createAttribute.name).toBe("Test Attribute");
    expect(res.data?.createAttribute.id).toBeDefined();
  });

  it("Given a duplicate code, when the form is submitted, then an error indicating the code already exists is shown.", async () => {
    const code = `DUP-ATTR-${Date.now()}`;
    await gql
      .mutation(createAttributeIdOnly, {
        code,
        name: "First Attribute",
      })
      .toPromise();

    await expect(
      gql
        .mutation(createAttributeIdOnly, {
          code,
          name: "Duplicate Attribute",
        })
        .toPromise(),
    ).rejects.toThrow();
  });

  it("Given a missing required field, when the form is submitted, then a validation error is shown.", async () => {
    await expect(
      gql
        .mutation(createAttributeIdOnly, {
          code: "",
          name: "",
        })
        .toPromise(),
    ).rejects.toThrow();
  });
});
