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

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

const createCategoryIdOnly = graphql(`
  mutation CreateCategoryForBrowse($code: String!, $name: String!) {
    createCategory(code: $code, name: $name) {
      id
    }
  }
`);

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

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

  it("Given categories exist, the category list displays a hierarchical tree", async () => {
    const code = `BROWSE-${Date.now()}`;
    await gql.mutation(createCategoryIdOnly, { code, name: "Browse Category" }).toPromise();

    const result = await gql.query(listCategories, {}).toPromise();

    expect(result.data?.productCategories.edges.length).toBeGreaterThan(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 list shows 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 product manager selects a category, they are navigated to the category detail screen", async () => {
    const code = `BROWSE-NAV-${Date.now()}`;
    const createResult = await gql
      .mutation(createCategoryIdOnly, { code, name: "Nav Category" })
      .toPromise();
    const categoryId = createResult.data!.createCategory.id;

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

    expect(result.data?.productCategory?.id).toBe(categoryId);
    expect(result.data?.productCategory?.code).toBe(code);
    expect(result.data?.productCategory?.name).toBe("Nav Category");
  });
});
