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

describe("deleteAccountingPeriod", () => {
  it("returns error when accounting period 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, AccountingPeriodNotFoundError);
  });

  it("returns error when accounting period has associated journal entries", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseAccountingPeriod], [baseJournalEntry]);

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

    expectErr(result, HasAssociatedJournalEntriesError);
  });

  it("deletes accounting period with no associated journal entries", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseAccountingPeriod], []);

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

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

  it("deletes accounting period with no associated journal entries", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseAccountingPeriod], []);

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

    expectOk(result);
    expect(mock.deletes.length).toBeGreaterThan(0);
  });
});
