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

describe("deleteProductAttributeValue", () => {
  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" }));

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

  it("returns error when parent attribute does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const orphanValue = { ...baseColorRed, attributeId: "nonexistent-attr" };
    mock.enqueueResults([orphanValue], []);

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

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

  it("returns error when value is in use on ACTIVE product", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseColorRed], [{ id: baseColorRed.attributeId }], [{ id: "variant-1" }]);

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

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

  it("deletes value and cleans up DRAFT product assignments", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseColorRed],
      [{ id: baseColorRed.attributeId }],
      [],
      [{ id: "draft-product-1" }],
    );

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.id).toBe(baseColorRed.id);
    }
    expect(mock.deletes).toHaveLength(2);
  });
});
