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

interface AttributeValue {
  id: string;
  label: string;
}

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

const getAttributeDetail = graphql(`
  query GetAttributeDetail($id: ID!) {
    productAttribute(id: $id) {
      id
      code
      name
      productAttributeValues {
        edges {
          node {
            id
            label
          }
        }
      }
    }
  }
`);

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

  it("Given an attribute with values, when the detail screen is opened, then the code, name, and all values are displayed.", async () => {
    const code = `VDET-${Date.now()}`;
    const createRes = await gql
      .mutation(createAttribute, {
        code,
        name: "Detailed Attribute",
        valueLabels: ["Alpha", "Beta", "Gamma"],
      })
      .toPromise();
    const attributeId = createRes.data!.createAttribute.id;

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

    const attr = res.data!.productAttribute!;
    expect(attr.id).toBe(attributeId);
    expect(attr.code).toBe(code);
    expect(attr.name).toBe("Detailed Attribute");
    const detailValues = attr.productAttributeValues.edges.map((e) => e.node) as AttributeValue[];
    expect(detailValues).toHaveLength(3);
    const labels = detailValues.map((v: AttributeValue) => v.label);
    expect(labels).toContain("Alpha");
    expect(labels).toContain("Beta");
    expect(labels).toContain("Gamma");
  });

  it("Given an attribute with no values, when the detail screen is opened, then an empty values list is shown.", async () => {
    const code = `EMPTY-${Date.now()}`;
    const createRes = await gql
      .mutation(createAttribute, {
        code,
        name: "Empty Attribute",
      })
      .toPromise();
    const attributeId = createRes.data!.createAttribute.id;

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

    const emptyAttr = res.data!.productAttribute!;
    expect(emptyAttr.id).toBe(attributeId);
    const emptyValues = emptyAttr.productAttributeValues.edges.map(
      (e) => e.node,
    ) as AttributeValue[];
    expect(emptyValues).toHaveLength(0);
  });
});
