import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import {
  baseInternalOrder,
  releasedInternalOrder,
  baseCostCenter,
  baseBudget,
} from "../testing/fixtures";
import { run } from "./getInternalOrder";

describe("getInternalOrder", () => {
  it("returns internal order with all fields when found by id", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseInternalOrder);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.internalOrder).toEqual(baseInternalOrder);
    }
  });

  it("returns internal order with responsible cost center reference populated", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseInternalOrder);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.internalOrder?.costCenterId).toEqual(baseCostCenter.id);
    }
  });

  it("returns internal order with budget assignment when one exists", async () => {
    const internalOrderWithBudget = { ...baseInternalOrder, budgetId: baseBudget.id };
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(internalOrderWithBudget);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.internalOrder).toEqual(internalOrderWithBudget);
    }
  });

  it("returns internal order without budget assignment when none exists", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(releasedInternalOrder);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.internalOrder?.status).toEqual("RELEASED");
    }
  });

  it("returns null when no internal order 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.internalOrder).toBeNull();
    }
  });
});
