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

describe("getPeriodByDate", () => {
  it("returns period when date falls within range", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue(baseAccountingPeriod);

    const result = await run(db, {
      companyId: "company-1",
      date: new Date("2024-01-15"),
    });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.accountingPeriod).toEqual(baseAccountingPeriod);
    }
  });

  it("returns null when no period covers the date", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue(undefined);

    const result = await run(db, {
      companyId: "company-1",
      date: new Date("2025-06-15"),
    });

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

  it("only returns OPERATING periods (not ADJUSTMENT)", async () => {
    const { db, spies } = createMockDb<DB>();
    // When no OPERATING period matches (e.g., only ADJUSTMENT exists), returns undefined
    spies.select.mockReturnValue(undefined);

    const result = await run(db, {
      companyId: "company-1",
      date: new Date("2024-01-15"),
    });

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