import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { baseCostElement, activeCostElement, secondaryCostElement } from "../testing/fixtures";
import { run } from "./getCostElement";

describe("getCostElement", () => {
  it("returns cost element with all fields when found by id", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseCostElement);

    const result = await run(db, { id: baseCostElement.id });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.costElement).toEqual(baseCostElement);
    }
  });

  it("returns primary cost element with GL account reference populated", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(activeCostElement);

    const result = await run(db, { id: activeCostElement.id });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.costElement).toEqual(activeCostElement);
      expect(result.value.costElement?.glAccountId).not.toBeNull();
    }
  });

  it("returns secondary cost element with GL account reference as null", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(secondaryCostElement);

    const result = await run(db, { id: secondaryCostElement.id });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.costElement).toEqual(secondaryCostElement);
      expect(result.value.costElement?.glAccountId).toBeNull();
    }
  });

  it("returns null when no cost element matches the given id", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { id: "non-existent" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.costElement).toBeNull();
    }
  });
});
