import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import { Transaction } from "../generated/kysely-tailordb";
import {
  CategoryNotActiveError,
  DuplicateUnitSymbolError,
  InvalidConversionFactorError,
  InvalidRoundingPrecisionError,
  UomCategoryNotFoundError,
} from "../lib/errors.generated";
import { baseUoMCategory, baseUnitKg } from "../testing/fixtures";
import { run } from "./createUnit";

describe("createUnit", () => {
  const inactiveCategory = {
    ...baseUoMCategory,
    isActive: false,
  };

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

    const result = await run(db, {
      categoryId: "nonexistent-category",
      name: "Ounce",
      symbol: "oz",
      conversionFactor: 0.0283495,
      roundingPrecision: 2,
    });

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

  it("throws when category is inactive", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue(inactiveCategory);

    const result = await run(db, {
      categoryId: inactiveCategory.id,
      name: "Ounce",
      symbol: "oz",
      conversionFactor: 0.0283495,
      roundingPrecision: 2,
    });

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

  it("throws when symbol already exists in category", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseUoMCategory) // Category lookup
      .mockReturnValueOnce(baseUnitKg); // Existing unit with same symbol

    const result = await run(db, {
      categoryId: baseUoMCategory.id,
      name: "Kilogram Duplicate",
      symbol: "kg",
      conversionFactor: 1.0,
      roundingPrecision: 2,
    });

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

  it("throws when conversion factor is not positive", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseUoMCategory) // Category lookup
      .mockReturnValueOnce(undefined); // No duplicate symbol

    const result = await run(db, {
      categoryId: baseUoMCategory.id,
      name: "Invalid Unit",
      symbol: "inv",
      conversionFactor: 0,
      roundingPrecision: 2,
    });

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

  it("throws when rounding precision is negative", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseUoMCategory) // Category lookup
      .mockReturnValueOnce(undefined); // No duplicate symbol

    const result = await run(db, {
      categoryId: baseUoMCategory.id,
      name: "Invalid Unit",
      symbol: "inv",
      conversionFactor: 1.0,
      roundingPrecision: -1,
    });

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

  // Success cases
  it("creates unit successfully", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const createdUnit = {
      id: "new-unit-id",
      name: "Ounce",
      symbol: "oz",
      categoryId: baseUoMCategory.id,
      conversionFactor: 0.0283495,
      roundingPrecision: 2,
      isActive: true,
      createdAt: new Date("2024-01-15T00:00:00.000Z"),
      updatedAt: null,
    };

    spies.select
      .mockReturnValueOnce(baseUoMCategory) // Category lookup
      .mockReturnValueOnce(undefined); // No duplicate symbol
    spies.insert.mockReturnValue(createdUnit);

    const result = await run(db, {
      categoryId: baseUoMCategory.id,
      name: "Ounce",
      symbol: "oz",
      conversionFactor: 0.0283495,
      roundingPrecision: 2,
    });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.unit.name).toBe("Ounce");
      expect(result.value.unit.symbol).toBe("oz");
      expect(result.value.unit.isActive).toBe(true);
    }
    expect(spies.insert).toHaveBeenCalled();
  });

  it("passes custom fields through to insert", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const createdUnit = {
      ...baseUnitKg,
      id: "new-unit-id",
      name: "Ounce",
      symbol: "oz",
      displayOrder: 5,
    };

    spies.select
      .mockReturnValueOnce(baseUoMCategory) // Category lookup
      .mockReturnValueOnce(undefined); // No duplicate symbol
    spies.insert.mockReturnValue(createdUnit);

    await run(db, {
      categoryId: baseUoMCategory.id,
      name: "Ounce",
      symbol: "oz",
      conversionFactor: 0.0283495,
      roundingPrecision: 2,
      displayOrder: 5,
    });

    expect(spies.values).toHaveBeenNthCalledWith(1, expect.objectContaining({ displayOrder: 5 }));
  });
});
