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

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

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

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

  it("deletes attribute and values successfully", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseColorAttribute) // attribute found
      .mockReturnValueOnce(undefined); // no assignments (executeTakeFirst)

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.id).toBe(baseColorAttribute.id);
    }
    expect(spies.delete).toHaveBeenCalled();
  });
});
