import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  BudgetNotFoundError,
  InvalidStateError,
  SelfApprovalNotAllowedError,
} from "../lib/errors.generated";
import { submittedBudget, baseBudget, baseUser } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./approveBudget";

// submittedBudget.createdByUserId === baseUser.id === "user-1"
// commandCtx.actorId === "test-actor" (different from creator)

describe("approveBudget", () => {
  it("approves a SUBMITTED budget transitioning it to APPROVED status", async () => {
    const approvedResult = { ...submittedBudget, status: "APPROVED" };
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(submittedBudget);
    spies.update.mockReturnValueOnce(approvedResult);

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

    const value = expectOk(result);
    expect(value.budget.status).toBe("APPROVED");
  });

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

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

    expectErr(result, BudgetNotFoundError);
  });

  it("returns error when budget is not in SUBMITTED status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseBudget); // DRAFT

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

    expectErr(result, InvalidStateError);
  });

  it("returns error when approver is the same as the budget creator", async () => {
    // createdByUserId = "user-1", set actorId to match
    const selfCtx = { ...commandCtx, actorId: baseUser.id };
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(submittedBudget);

    const result = await run(db, { budgetId: submittedBudget.id }, selfCtx);

    expectErr(result, SelfApprovalNotAllowedError);
  });

  it("emits audit event recording the status transition and approver", async () => {
    const approvedResult = { ...submittedBudget, status: "APPROVED" };
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(submittedBudget);
    spies.update.mockReturnValueOnce(approvedResult);

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

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