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

describe("submitBudget", () => {
  it("submits a DRAFT budget with line items transitioning it to SUBMITTED status", async () => {
    const updatedBudget = { ...baseBudget, status: "SUBMITTED" };
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseBudget).mockReturnValueOnce(baseBudgetLineItem);
    spies.update.mockReturnValueOnce(updatedBudget);

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

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

  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 DRAFT status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(submittedBudget);

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

    expectErr(result, InvalidStateError);
  });

  it("returns error when budget has no line items", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseBudget).mockReturnValueOnce(undefined); // no line items

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

    expectErr(result, NoLineItemsError);
  });

  it("emits audit event recording the status transition and acting user", async () => {
    const updatedBudget = { ...baseBudget, status: "SUBMITTED" };
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseBudget).mockReturnValueOnce(baseBudgetLineItem);
    spies.update.mockReturnValueOnce(updatedBudget);

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

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