import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  AccountingPeriodNotFoundError,
  HasAssociatedJournalEntriesError,
  HasActivePeriodCloseError,
} from "../lib/errors.generated";
import { baseAccountingPeriod, baseJournalEntry, basePeriodClose } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./deleteAccountingPeriod";

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

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

    expectErr(result, AccountingPeriodNotFoundError);
  });

  it("returns error when accounting period has associated journal entries", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseAccountingPeriod).mockReturnValueOnce(baseJournalEntry);

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

    expectErr(result, HasAssociatedJournalEntriesError);
  });

  it("returns error when accounting period has an active period close record", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseAccountingPeriod)
      .mockReturnValueOnce(undefined)
      .mockReturnValueOnce(basePeriodClose);

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

    expectErr(result, HasActivePeriodCloseError);
  });

  it("deletes accounting period with no associated journal entries or period close", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseAccountingPeriod)
      .mockReturnValueOnce(undefined)
      .mockReturnValueOnce(undefined);
    spies.delete.mockReturnValueOnce(undefined);

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

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

  it("emits audit event recording acting user, timestamp, and deleted period details", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseAccountingPeriod)
      .mockReturnValueOnce(undefined)
      .mockReturnValueOnce(undefined);
    spies.delete.mockReturnValueOnce(undefined);

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

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