import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import { Transaction } 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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined); // attribute not found

    const result = await run(db, { 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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseColorAttribute); // attribute found

    const result = await run(db, { 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 { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseColorAttribute) // attribute found
      .mockReturnValueOnce(baseColorRed); // existing value with same label

    const result = await run(db, { attributeId: baseColorAttribute.id, label: "Red" });

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

  it("creates value successfully", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const createdValue = { ...baseColorRed, id: "new-value-id", label: "Green" };

    spies.select
      .mockReturnValueOnce(baseColorAttribute) // attribute found
      .mockReturnValueOnce(undefined); // no duplicate label
    spies.insert.mockReturnValue(createdValue);

    const result = await run(db, { attributeId: baseColorAttribute.id, label: "Green" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.productAttributeValue.label).toBe("Green");
    }
    expect(spies.insert).toHaveBeenCalled();
  });
});
