import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import { Transaction } from "../generated/kysely-tailordb";
import { UnitNotFoundError, UnitNotInCategoryError } from "../lib/errors.generated";
import { baseUoMCategory, baseUnitGram, baseUnitKg, baseUnitLiter } from "../testing/fixtures";
import { run } from "./setReferenceUnit";

describe("setReferenceUnit", () => {
  // Error cases
  it("throws when unit doesn't exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue(undefined);

    const result = await run(db, {
      unitId: "nonexistent-unit",
      categoryId: baseUoMCategory.id,
    });

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

  it("throws when unit is not in specified category", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue(baseUnitLiter); // Unit is in category-2, not category-1

    const result = await run(db, {
      unitId: baseUnitLiter.id,
      categoryId: baseUoMCategory.id, // category-1
    });

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

  // Idempotent cases
  it("returns category unchanged when unit is already reference", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseUnitKg) // Unit lookup
      .mockReturnValueOnce(baseUoMCategory); // Category lookup

    const result = await run(db, {
      unitId: baseUnitKg.id,
      categoryId: baseUoMCategory.id,
    });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.uoMCategory.referenceUnitId).toBe(baseUnitKg.id);
    }
    expect(spies.update).not.toHaveBeenCalled();
  });

  // Success cases
  it("changes reference unit and recalculates conversion factors", async () => {
    const { db, spies } = createMockDb<Transaction>();
    // gram has conversion factor 0.001 (1g = 0.001kg)
    // When gram becomes reference, kg should become 1000 (1kg = 1000g)
    const updatedCategory = {
      ...baseUoMCategory,
      referenceUnitId: baseUnitGram.id,
      updatedAt: new Date("2024-01-15T00:00:00.000Z"),
    };

    spies.select
      .mockReturnValueOnce(baseUnitGram) // Unit lookup
      .mockReturnValueOnce(baseUoMCategory) // Category lookup
      .mockReturnValueOnce([baseUnitKg, baseUnitGram]); // All units in category
    spies.update
      .mockReturnValueOnce({ ...baseUnitKg, conversionFactor: 1000 }) // Update kg factor
      .mockReturnValueOnce({ ...baseUnitGram, conversionFactor: 1.0 }) // Update gram factor
      .mockReturnValueOnce(updatedCategory); // Update category

    const result = await run(db, {
      unitId: baseUnitGram.id,
      categoryId: baseUoMCategory.id,
    });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.uoMCategory.referenceUnitId).toBe(baseUnitGram.id);
    }
    expect(spies.update).toHaveBeenCalled();
  });
});
