import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { FiscalYearNotFoundError, HasAssociatedPeriodsError } from "../lib/errors.generated";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { baseFiscalYear, baseAccountingPeriod } from "../testing/fixtures";
import { run } from "./deleteFiscalYear";

describe("deleteFiscalYear", () => {
  it("returns error when fiscal year does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) => run(trx, { id: "non-existent" }, commandCtx));

    expectErr(result, FiscalYearNotFoundError);
  });

  it("returns error when fiscal year has associated accounting periods", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseFiscalYear], [baseAccountingPeriod]);

    const result = await mock.withTx((trx) => run(trx, { id: baseFiscalYear.id }, commandCtx));

    expectErr(result, HasAssociatedPeriodsError);
  });

  it("deletes fiscal year with no associated accounting periods", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseFiscalYear], []);

    const result = await mock.withTx((trx) => run(trx, { id: baseFiscalYear.id }, commandCtx));

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