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

const listUnits = graphql(`
  query ListUnits {
    units {
      edges {
        node {
          id
        }
      }
    }
  }
`);

const createProductIdOnly = graphql(`
  mutation CreateProductIdOnly($code: String!, $name: String!, $description: String, $unitId: ID!) {
    createProduct(code: $code, name: $name, description: $description, unitId: $unitId) {
      id
    }
  }
`);

const getProductDetail = graphql(`
  query GetProductDetail($id: ID!) {
    product(id: $id) {
      id
      code
      name
      description
      status
    }
  }
`);

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

  it("Given an existing product, when the detail screen is opened by a viewer, then all fields are displayed without edit or action controls.", async () => {
    const unitsResult = await gql.query(listUnits, {}).toPromise();
    const uomId = unitsResult.data!.units.edges[0].node.id;

    const createResult = await gql
      .mutation(createProductIdOnly, {
        code: `VIEW-${Date.now()}`,
        name: "Viewer Detail Product",
        description: "Viewer description",
        unitId: uomId,
      })
      .toPromise();
    const productId = createResult.data!.createProduct.id;

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

    expect(res.data?.product?.id).toBe(productId);
    expect(res.data?.product?.code).toBeDefined();
    expect(res.data?.product?.name).toBe("Viewer Detail Product");
    expect(res.data?.product?.description).toBe("Viewer description");
    expect(res.data?.product?.status).toBe("DRAFT");
  });
});
