import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) =>
      run(trx, {
        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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseUnitLiter]); // Unit is in category-2, not category-1

    const result = await mock.withTx((trx) =>
      run(trx, {
        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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseUnitKg], // Unit lookup
      [baseUoMCategory], // Category lookup
    );

    const result = await mock.withTx((trx) =>
      run(trx, {
        unitId: baseUnitKg.id,
        categoryId: baseUoMCategory.id,
      }),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.uoMCategory.referenceUnitId).toBe(baseUnitKg.id);
    }
    expect(mock.updates).toHaveLength(0);
  });

  // Success cases
  it("changes reference unit and recalculates conversion factors", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    // 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"),
    };

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

    const result = await mock.withTx((trx) =>
      run(trx, {
        unitId: baseUnitGram.id,
        categoryId: baseUoMCategory.id,
      }),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.uoMCategory.referenceUnitId).toBe(baseUnitGram.id);
    }
    expect(mock.updates.length).toBeGreaterThan(0);
  });
});
