import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  AttributeNotFoundError,
  InvalidLabelError,
  DuplicateValueError,
} from "../lib/errors.generated";
import { baseColorAttribute, baseColorRed } from "../testing/fixtures";
import { run } from "./createProductAttributeValue";

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

    const result = await mock.withTx((trx) =>
      run(trx, { attributeId: "nonexistent", label: "Red" }),
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(AttributeNotFoundError);
    }
  });

  it("returns error when label is empty", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseColorAttribute]);

    const result = await mock.withTx((trx) =>
      run(trx, { attributeId: baseColorAttribute.id, label: "" }),
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidLabelError);
    }
  });

  it("returns error when label already exists", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseColorAttribute], [baseColorRed]);

    const result = await mock.withTx((trx) =>
      run(trx, { attributeId: baseColorAttribute.id, label: "Red" }),
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(DuplicateValueError);
    }
  });

  it("creates value successfully", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const createdValue = { ...baseColorRed, id: "new-value-id", label: "Green" };

    mock.enqueueResults([baseColorAttribute], [], [createdValue]);

    const result = await mock.withTx((trx) =>
      run(trx, { attributeId: baseColorAttribute.id, label: "Green" }),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.productAttributeValue.label).toBe("Green");
    }
    expect(mock.inserts.length).toBeGreaterThan(0);
  });
});
