import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  FinancialStatementNotFoundError,
  StatementAlreadyFinalizedError,
  TrialBalanceNotFoundError,
  TrialBalanceImbalancedError,
  ComparativeTrialBalanceNotFoundError,
} from "../lib/errors.generated";
import {
  baseFinancialStatement,
  finalizedFinancialStatement,
  baseTrialBalance,
  baseTrialBalanceLine,
  baseAccount,
} from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./regenerateFinancialStatement";

describe("regenerateFinancialStatement", () => {
  it("returns error when financial statement does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined); // statement lookup

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

    expectErr(result, FinancialStatementNotFoundError);
  });

  it("returns error when financial statement is already FINALIZED", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(finalizedFinancialStatement); // statement lookup

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

    expectErr(result, StatementAlreadyFinalizedError);
  });

  it("returns error when trial balance is not found", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseFinancialStatement); // statement lookup
    spies.select.mockReturnValueOnce(undefined); // trial balance lookup

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

    expectErr(result, TrialBalanceNotFoundError);
  });

  it("returns error when trial balance is imbalanced", async () => {
    const imbalancedTrialBalance = {
      ...baseTrialBalance,
      isBalanced: false,
      totalDebits: 10000,
      totalCredits: 9000,
    };
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseFinancialStatement); // statement lookup
    spies.select.mockReturnValueOnce(imbalancedTrialBalance); // trial balance lookup

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

    expectErr(result, TrialBalanceImbalancedError);
  });

  it("returns error when comparative trial balance is not found", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const statementWithComparative = {
      ...baseFinancialStatement,
      comparativePeriodTrialBalanceId: "comparative-tb-1",
    };
    spies.select.mockReturnValueOnce(statementWithComparative); // statement lookup
    spies.select.mockReturnValueOnce(baseTrialBalance); // trial balance lookup
    spies.select.mockReturnValueOnce(undefined); // comparative trial balance lookup - not found

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

    expectErr(result, ComparativeTrialBalanceNotFoundError);
  });

  it("regenerates statement with fresh data and updates generatedAt", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedStatement = {
      ...baseFinancialStatement,
      generatedAt: new Date(),
      updatedAt: new Date(),
    };

    spies.select.mockReturnValueOnce(baseFinancialStatement); // statement lookup
    spies.select.mockReturnValueOnce(baseTrialBalance); // trial balance lookup
    spies.select.mockReturnValueOnce([baseTrialBalanceLine]); // trial balance lines (execute)
    spies.select.mockReturnValueOnce(baseAccount); // account lookup for line
    spies.insert.mockReturnValue({}); // line item insert
    spies.update.mockReturnValueOnce(updatedStatement); // statement update

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

    const value = expectOk(result);
    expect(value.financialStatement).toBeDefined();
    expect(value.financialStatement.generatedAt).toBeDefined();
  });

  it("emits audit event recording statement regeneration", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedStatement = {
      ...baseFinancialStatement,
      generatedAt: new Date(),
      updatedAt: new Date(),
    };

    spies.select.mockReturnValueOnce(baseFinancialStatement); // statement lookup
    spies.select.mockReturnValueOnce(baseTrialBalance); // trial balance lookup
    spies.select.mockReturnValueOnce([baseTrialBalanceLine]); // trial balance lines (execute)
    spies.select.mockReturnValueOnce(baseAccount); // account lookup for line
    spies.insert.mockReturnValue({}); // line item insert
    spies.update.mockReturnValueOnce(updatedStatement); // statement update

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

    const value = expectOk(result);
    expect(value.auditTrail).toBeDefined();
    expect(value.auditTrail).toContainEqual(
      expect.objectContaining({
        type: "STATEMENT_REGENERATED",
        actorId: commandCtx.actorId,
      }),
    );
  });
});
