import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { DeleteNotAllowedError, ProductNotFoundError } from "../lib/errors.generated";
import { baseActiveProduct, baseDraftProduct } from "../testing/fixtures";
import { run } from "./deleteProduct";

describe("deleteProduct", () => {
  it("returns error when product not found", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);
    const result = await run(db, { id: "nonexistent" });
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(ProductNotFoundError);
    }
  });

  it("returns error when not DRAFT", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce({ ...baseActiveProduct });
    const result = await run(db, { id: "product-2" });
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(DeleteNotAllowedError);
    }
  });

  it("deletes DRAFT product and associated records", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce({ ...baseDraftProduct });
    // delete calls for ProductAttributeAssignment, ProductCategoryAssignment, Product
    spies.delete.mockReturnValueOnce([]);
    spies.delete.mockReturnValueOnce([]);
    spies.delete.mockReturnValueOnce([]);
    const result = await run(db, { id: "product-1" });
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.id).toBe("product-1");
    }
  });
});
