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

    const result = await run(db, { 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 { db, spies } = createMockDb<Transaction>();
    const orphanValue = { ...baseColorRed, attributeId: "nonexistent-attr" };
    spies.select
      .mockReturnValueOnce(orphanValue) // value found
      .mockReturnValueOnce(undefined); // attribute not found

    const result = await run(db, { 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 { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseColorRed) // value found
      .mockReturnValueOnce({ id: baseColorRed.attributeId }) // attribute exists
      .mockReturnValueOnce({ id: "variant-1" }); // join query finds active variant usage

    const result = await run(db, { 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 { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseColorRed) // value found
      .mockReturnValueOnce({ id: baseColorRed.attributeId }) // attribute exists
      .mockReturnValueOnce(undefined); // no active variant usage

    const result = await run(db, { id: baseColorRed.id });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.id).toBe(baseColorRed.id);
    }
    // Should have called delete twice: once for assignment cleanup, once for value deletion
    expect(spies.delete).toHaveBeenCalledTimes(2);
  });
});
