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

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

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

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

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

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

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

  it("deletes attribute and values successfully", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseColorAttribute], []);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.id).toBe(baseColorAttribute.id);
    }
    expect(mock.deletes.length).toBeGreaterThan(0);
  });
});
