import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseAccountingPeriod]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.accountingPeriod).toEqual(baseAccountingPeriod);
    }
    expect(mock.selects).toHaveLength(1);
    expect(mock.selects[0].parameters).toContain("company-1");
    expect(mock.selects[0].parameters).toContain("OPERATING");
    expect(mock.selects[0].sql).toMatch(/"companyId"/);
    expect(mock.selects[0].sql).toMatch(/"periodType"/);
    expect(mock.selects[0].sql).toMatch(/"startDate"/);
    expect(mock.selects[0].sql).toMatch(/"endDate"/);
  });

  it("returns null when no period covers the date", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await run(mock.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 mock = createKyselyMock<Namespace["main-db"]>();
    // When no OPERATING period matches (e.g., only ADJUSTMENT exists), returns undefined
    mock.enqueueResults([]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.accountingPeriod).toBeNull();
    }
    expect(mock.selects[0].parameters).toContain("OPERATING");
    expect(mock.selects[0].sql).toMatch(/"periodType"/);
  });
});
