import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { JournalEntryNotFoundError, InvalidStatusForDeleteError } from "../lib/errors.generated";
import { baseJournalEntry, postedJournalEntry, reversedJournalEntry } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./deleteJournalEntry";

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

    const result = await run(db, { journalEntryId: "missing-entry" }, commandCtx);

    expectErr(result, JournalEntryNotFoundError);
  });

  it("returns error when journal entry is in POSTED status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(postedJournalEntry);

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

    expectErr(result, InvalidStatusForDeleteError);
  });

  it("returns error when journal entry is in REVERSED status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(reversedJournalEntry);

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

    expectErr(result, InvalidStatusForDeleteError);
  });

  it("deletes DRAFT journal entry and all associated journal lines", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseJournalEntry);

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

    const value = expectOk(result);
    expect(value.journalEntryId).toBe(baseJournalEntry.id);
    // Verify journal lines were deleted first, then the entry
    expect(spies.delete).toHaveBeenCalledTimes(2);
  });

  it("emits audit event recording the deletion and acting user", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseJournalEntry);

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

    expectOk(result);
    expect(spies.delete).toHaveBeenCalled();
  });
});
