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

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

    const result = await mock.withTx((trx) =>
      run(trx, { journalEntryId: "missing-entry" }, commandCtx),
    );

    expectErr(result, JournalEntryNotFoundError);
  });

  it("returns error when journal entry is in POSTED status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([postedJournalEntry]);

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

    expectErr(result, InvalidStatusForCancelError);
  });

  it("transitions DRAFT journal entry to CANCELLED without deleting lines", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseJournalEntry], [{ ...baseJournalEntry, status: "CANCELLED" }]);

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

    const value = expectOk(result);
    expect(value.journalEntry.status).toBe("CANCELLED");
    expect(mock.deletes).toHaveLength(0);
    expect(mock.updates).toHaveLength(1);
  });
});
