import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import {
  baseBudget,
  baseBudgetLineItem,
  activeCostElement,
  baseAccountingPeriod,
} from "../testing/fixtures";
import { run } from "./getBudget";

describe("getBudget", () => {
  it("returns budget with all header fields and line items when found by id", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseBudget).mockReturnValueOnce([baseBudgetLineItem]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.budget).toEqual(baseBudget);
      expect(result.value.lineItems).toEqual([baseBudgetLineItem]);
    }
  });

  it("returns budget line items with cost element, period, and planned amount", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseBudget).mockReturnValueOnce([baseBudgetLineItem]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.lineItems[0]).toMatchObject({
        costElementId: activeCostElement.id,
        accountingPeriodId: baseAccountingPeriod.id,
        plannedAmount: baseBudgetLineItem.plannedAmount,
      });
    }
  });

  it("returns budget line items with derived GL account from cost element mapping", async () => {
    const lineItemWithGlAccount = { ...baseBudgetLineItem, glAccountId: "account-1" };
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseBudget).mockReturnValueOnce([lineItemWithGlAccount]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.lineItems[0].glAccountId).toEqual("account-1");
    }
  });

  it("returns budget with empty line items when budget has no line items", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseBudget).mockReturnValueOnce([]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.budget).toEqual(baseBudget);
      expect(result.value.lineItems).toEqual([]);
    }
  });

  it("returns null when no budget 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.budget).toBeNull();
      expect(result.value.lineItems).toEqual([]);
    }
  });
});
