import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } 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,
    status: "INACTIVE" as const,
  };

  // Error cases
  it("throws when category doesn't exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

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

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

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

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

    const result = await mock.withTx((trx) =>
      run(trx, {
        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 mock = createKyselyMock<Namespace["main-db"]>();
    const createdUnit = {
      id: "new-unit-id",
      name: "Ounce",
      symbol: "oz",
      categoryId: baseUoMCategory.id,
      conversionFactor: 0.0283495,
      roundingPrecision: 2,
      status: "ACTIVE" as const,
      createdAt: new Date("2024-01-15T00:00:00.000Z"),
      updatedAt: null,
    };

    mock.enqueueResults(
      [baseUoMCategory], // Category lookup
      [], // No duplicate symbol
      [createdUnit],
    );

    const result = await mock.withTx((trx) =>
      run(trx, {
        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.status).toBe("ACTIVE");
    }
    expect(mock.inserts.length).toBeGreaterThan(0);
  });

  it("passes custom fields through to insert", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const createdUnit = {
      ...baseUnitKg,
      id: "new-unit-id",
      name: "Ounce",
      symbol: "oz",
      displayOrder: 5,
    };

    mock.enqueueResults(
      [baseUoMCategory], // Category lookup
      [], // No duplicate symbol
      [createdUnit],
    );

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

    expect(mock.inserts[0].insertValues()).toEqual(expect.objectContaining({ displayOrder: 5 }));
  });
});
