import { describe, it, expect } from "vitest";
import { uuidv5 } from "../../../shared/uuidv5";
import { uomCategories } from "./uomCategories";
import { units, unitIds } from "./units";
import { currencies, currencyIds } from "./currencies";
import { exchangeRates } from "./exchangeRates";

describe("primitives seed data", () => {
  describe("uuid determinism", () => {
    it("produces stable IDs across calls", () => {
      const id1 = uuidv5("erp-kit:primitives", "currency:USD");
      const id2 = uuidv5("erp-kit:primitives", "currency:USD");
      expect(id1).toBe(id2);
      expect(id1).toBe(currencyIds.USD);
    });
  });

  describe("uomCategories", () => {
    it("has all expected categories", () => {
      const names = Object.values(uomCategories).map((c) => c.name);
      expect(names).toEqual(["Weight", "Length", "Volume", "Area", "Time", "Quantity"]);
    });

    it("all entries are active", () => {
      for (const row of Object.values(uomCategories)) {
        expect(row.isActive).toBe(true);
      }
    });
  });

  describe("units", () => {
    it("every unit references a valid category", () => {
      const categoryIds = new Set(Object.keys(uomCategories));
      for (const [id, row] of Object.entries(units)) {
        expect(categoryIds.has(row.categoryId), `unit ${id} references missing category ${row.categoryId}`).toBe(true);
      }
    });

    it("reference units have conversionFactor 1", () => {
      const referenceUnits = [unitIds.kg, unitIds.m, unitIds.L, unitIds.sqm, unitIds.hr, unitIds.ea];
      for (const id of referenceUnits) {
        expect(units[id].conversionFactor).toBe(1);
      }
    });

    it("has unique symbols", () => {
      const symbols = Object.values(units).map((u) => u.symbol);
      expect(new Set(symbols).size).toBe(symbols.length);
    });
  });

  describe("currencies", () => {
    it("has exactly one base currency", () => {
      const baseCurrencies = Object.values(currencies).filter((c) => c.isBaseCurrency);
      expect(baseCurrencies).toHaveLength(1);
      expect(baseCurrencies[0].code).toBe("USD");
    });

    it("has unique codes", () => {
      const codes = Object.values(currencies).map((c) => c.code);
      expect(new Set(codes).size).toBe(codes.length);
    });
  });

  describe("exchangeRates", () => {
    it("all rates reference valid currencies", () => {
      const cIds = new Set(Object.keys(currencies));
      for (const [id, row] of Object.entries(exchangeRates)) {
        expect(cIds.has(row.sourceCurrencyId), `rate ${id} references missing source ${row.sourceCurrencyId}`).toBe(true);
        expect(cIds.has(row.targetCurrencyId), `rate ${id} references missing target ${row.targetCurrencyId}`).toBe(true);
      }
    });

    it("all rates are positive", () => {
      for (const row of Object.values(exchangeRates)) {
        expect(row.rate).toBeGreaterThan(0);
      }
    });
  });
});
