import { Injectable } from '@nestjs/common';
import type { Currency, JournalSourceType, LedgerDirection, Prisma } from '@prisma/client';
import { Decimal, sum } from '@rms/domain';

export interface LedgerLineInput {
  accountId: string;
  direction: LedgerDirection;
  amount: Decimal.Value;
  leaseId?: string | null;
  tenantId?: string | null;
  invoiceId?: string | null;
}

export interface PostEntryInput {
  organizationId: string;
  entryDate: Date;
  sourceType: JournalSourceType;
  sourceId: string;
  // One entry is always a single currency (no FX), so DR==CR stays meaningful and
  // each currency's books balance independently. Stamped on the entry and lines.
  currency: Currency;
  memo?: string;
  createdById?: string | null;
  lines: LedgerLineInput[];
}

/**
 * The one and only writer of financial truth. Every money movement is an
 * append-only, balanced double-entry journal entry — the ledger can never be
 * updated or deleted, only reversed. Refuses to post an unbalanced entry.
 */
@Injectable()
export class LedgerService {
  async post(tx: Prisma.TransactionClient, input: PostEntryInput) {
    if (input.lines.length < 2) {
      throw new Error('A journal entry needs at least two lines (a debit and a credit)');
    }
    // Amounts are always positive; sign is expressed by direction. This keeps the
    // DR=CR check meaningful (a negative amount could otherwise mask a mis-mapping).
    for (const l of input.lines) {
      if (new Decimal(l.amount.toString()).lte(0)) {
        throw new Error('Ledger line amounts must be positive; use direction (DEBIT/CREDIT) for sign');
      }
    }
    const debit = sum(input.lines.filter((l) => l.direction === 'DEBIT').map((l) => l.amount.toString()));
    const credit = sum(input.lines.filter((l) => l.direction === 'CREDIT').map((l) => l.amount.toString()));
    if (!debit.equals(credit)) {
      throw new Error(`Unbalanced journal entry: DR ${debit.toFixed(2)} != CR ${credit.toFixed(2)}`);
    }
    if (debit.isZero()) {
      throw new Error('Refusing to post a zero-value journal entry');
    }

    return tx.journalEntry.create({
      data: {
        organizationId: input.organizationId,
        entryDate: input.entryDate,
        sourceType: input.sourceType,
        sourceId: input.sourceId,
        currency: input.currency,
        memo: input.memo,
        createdById: input.createdById ?? null,
        lines: {
          create: input.lines.map((l) => ({
            accountId: l.accountId,
            direction: l.direction,
            amount: new Decimal(l.amount.toString()).toFixed(2),
            currency: input.currency,
            leaseId: l.leaseId ?? null,
            tenantId: l.tenantId ?? null,
            invoiceId: l.invoiceId ?? null,
          })),
        },
      },
      include: { lines: true },
    });
  }

  /** Posts a mirror entry that flips every line's direction, cancelling the
   * original. Append-only: the original is never touched. Idempotent guard —
   * an entry can only be reversed once. */
  async reverse(
    tx: Prisma.TransactionClient,
    input: { entryId: string; entryDate: Date; memo?: string; createdById?: string | null },
  ) {
    const original = await tx.journalEntry.findFirstOrThrow({
      where: { id: input.entryId },
      include: { lines: true },
    });
    const existing = await tx.journalEntry.findFirst({ where: { reversesId: original.id } });
    if (existing) throw new Error('This journal entry has already been reversed');

    return tx.journalEntry.create({
      data: {
        organizationId: original.organizationId,
        entryDate: input.entryDate,
        sourceType: 'REVERSAL',
        sourceId: original.sourceId,
        currency: original.currency,
        memo: input.memo ?? `Reversal of entry ${original.id}`,
        reversesId: original.id,
        createdById: input.createdById ?? null,
        lines: {
          create: original.lines.map((l) => ({
            accountId: l.accountId,
            direction: l.direction === 'DEBIT' ? 'CREDIT' : 'DEBIT',
            amount: l.amount,
            currency: l.currency,
            leaseId: l.leaseId,
            tenantId: l.tenantId,
            invoiceId: l.invoiceId,
          })),
        },
      },
      include: { lines: true },
    });
  }
}
