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

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

const listAttributes = graphql(`
  query ListProductAttributes {
    productAttributes {
      edges {
        node {
          id
          code
          name
        }
      }
    }
  }
`);

const getAttribute = graphql(`
  query GetProductAttribute($id: ID!) {
    productAttribute(id: $id) {
      id
      code
      name
    }
  }
`);

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

  it("Given attributes exist, when the attribute list is opened, then each attribute is shown with its code, name, and value count.", async () => {
    const code = `LIST-${Date.now()}`;
    await gql
      .mutation(createAttribute, {
        code,
        name: "Browsable Attribute",
        valueLabels: ["A", "B", "C"],
      })
      .toPromise();

    const res = await gql.query(listAttributes, {}).toPromise();

    expect(res.data?.productAttributes.edges.length).toBeGreaterThan(0);
    const node = res.data?.productAttributes.edges[0].node;
    expect(node?.id).toBeDefined();
    expect(node?.code).toBeDefined();
    expect(node?.name).toBeDefined();
  });

  it("Given the attribute list is displayed, when an attribute is selected, then the attribute detail screen is shown.", async () => {
    const code = `DETAIL-${Date.now()}`;
    const createRes = await gql
      .mutation(createAttribute, {
        code,
        name: "Detail Attribute",
        valueLabels: ["X"],
      })
      .toPromise();
    const attributeId = createRes.data!.createAttribute.id;

    const res = await gql.query(getAttribute, { id: attributeId }).toPromise();

    const detailAttr = res.data!.productAttribute!;
    expect(detailAttr.id).toBe(attributeId);
    expect(detailAttr.code).toBe(code);
    expect(detailAttr.name).toBe("Detail Attribute");
  });
});
