import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { FiscalYearNotFoundError, HasAssociatedPeriodsError } from "../lib/errors.generated";
import { baseFiscalYear, baseAccountingPeriod } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./deleteFiscalYear";

describe("deleteFiscalYear", () => {
  it("returns error when fiscal year does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);

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

    expectErr(result, FiscalYearNotFoundError);
  });

  it("returns error when fiscal year has associated accounting periods", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseFiscalYear).mockReturnValueOnce(baseAccountingPeriod);

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

    expectErr(result, HasAssociatedPeriodsError);
  });

  it("deletes fiscal year with no associated accounting periods", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseFiscalYear).mockReturnValueOnce(undefined);
    spies.delete.mockReturnValueOnce(undefined);

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

    const value = expectOk(result);
    expect(value.deleted).toBe(true);
  });
});
