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

const listCategories = graphql(`
  query ListCategoriesViewer {
    productCategories {
      edges {
        node {
          id
          code
          name
        }
      }
    }
  }
`);

const getCategory = graphql(`
  query GetCategoryViewer($id: ID!) {
    productCategory(id: $id) {
      id
      code
      name
    }
  }
`);

describe("viewer--browse-category-list", () => {
  const gql = createGraphQLClient(inject("url"), inject("token"));

  it("Given categories exist, the viewer sees the hierarchical tree without mutation actions", async () => {
    const result = await gql.query(listCategories, {}).toPromise();

    expect(result.data?.productCategories.edges).toBeDefined();
    if (result.data!.productCategories.edges.length > 0) {
      const node = result.data?.productCategories.edges[0].node;
      expect(node?.id).toBeDefined();
      expect(node?.code).toBeDefined();
      expect(node?.name).toBeDefined();
    }
  });

  it("Given no categories exist, the viewer sees an empty state", async () => {
    const result = await gql.query(listCategories, {}).toPromise();

    expect(result.data?.productCategories.edges).toBeDefined();
    expect(Array.isArray(result.data?.productCategories.edges)).toBe(true);
  });

  it("Given the viewer selects a category, they are navigated to the category detail screen", async () => {
    const listResult = await gql.query(listCategories, {}).toPromise();

    if (listResult.data!.productCategories.edges.length > 0) {
      const categoryId = listResult.data!.productCategories.edges[0].node.id;

      const result = await gql.query(getCategory, { id: categoryId }).toPromise();

      expect(result.data?.productCategory?.id).toBe(categoryId);
      expect(result.data?.productCategory?.code).toBeDefined();
      expect(result.data?.productCategory?.name).toBeDefined();
    }
  });
});
