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

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

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

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

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

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

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

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

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

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

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

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

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

  it("updates label successfully", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updatedValue = { ...baseColorRed, label: "Crimson" };

    mock.enqueueResults([baseColorRed], [], [updatedValue]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.value.label).toBe("Crimson");
    }
    expect(mock.updates.length).toBeGreaterThan(0);
  });
});
