import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { baseVariant } from "../testing/fixtures";
import { run } from "./getProductVariant";

describe("getProductVariant", () => {
  it("returns variant by id", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseVariant]);

    const result = await run(mock.db, { id: "variant-1" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.variant).toEqual(baseVariant);
    }

    expect(mock.selects).toHaveLength(1);
    expect(mock.selects[0].sql).toMatch(/"id"/);
    expect(mock.selects[0].parameters).toContain("variant-1");
  });

  it("returns variant by productId and axisValueKey", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseVariant]);

    const result = await run(mock.db, { productId: "product-2", axisValueKey: "value-1|value-3" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.variant).toEqual(baseVariant);
    }

    expect(mock.selects).toHaveLength(1);
    expect(mock.selects[0].sql).toMatch(/"productId"/);
    expect(mock.selects[0].sql).toMatch(/"axisValueKey"/);
    expect(mock.selects[0].parameters).toContain("product-2");
    expect(mock.selects[0].parameters).toContain("value-1|value-3");
  });

  it("returns null when not found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await run(mock.db, { id: "nonexistent" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.variant).toBeNull();
    }
  });
});
