import {
  BadRequestException,
  ForbiddenException,
  Injectable,
  NotFoundException,
} from '@nestjs/common';
import { ClsService } from 'nestjs-cls';
import type { EntityManager } from 'typeorm';
import { CashHeldRepository, CashHeldEventRow } from './repositories/cash-held.repository';
import { BankAccountService } from '../bank-account/bank-account.service';
import { AuditService } from '../audit/audit.service';
import { CLS_USER_PERMISSIONS } from '../../common/cls/cls.constants';
import { AccessLevel } from '../../entities/role-permission.entity';
import {
  CashHeldMovementEntity,
  type CashHeldMovementType,
} from '../../entities/cash-held-movement.entity';
import { CashHolder, ResolvedCashHolder, cashHolderKey } from './cash-holder';
import {
  CashHeldCustomerUseDto,
  CashHeldHistoryQueryDto,
  CashHeldHoldersQueryDto,
  CashHeldReturnDto,
  CashHeldTransferDto,
} from './dto';

const LEVEL: Record<string, number> = { none: 0, view: 1, create: 2, edit: 3, delete: 4 };
const r2 = (n: number) => Math.round(n * 100) / 100;

/**
 * Cash Held at destination (client 2026-10-19,
 * docs/cash-held-at-destination-plan.md). Company cash handed over at
 * the destination (Settlements → Cash collection for MD) is held by own
 * staff or a supplier's driver until the accountant uses it:
 * A pay a supplier (via Pay Supplier), B use for a customer,
 * C transfer to another holder, D return to the office bank.
 * Every spend is checked against the holder's balance under a lock.
 */
@Injectable()
export class CashHeldService {
  constructor(
    private readonly repo: CashHeldRepository,
    private readonly bankAccounts: BankAccountService,
    private readonly audit: AuditService,
    private readonly cls: ClsService,
  ) {}

  listHolders(query: CashHeldHoldersQueryDto) {
    return this.repo.listHolders(query);
  }

  /** History with a running balance (pending receipts don't count). */
  async history(query: CashHeldHistoryQueryDto) {
    const events = await this.repo.history(query.holder_key, query.currency_id);
    let balance = 0;
    const rows: Array<CashHeldEventRow & { balance: number }> = events.map((e) => {
      if (e.direction === 'IN') balance = r2(balance + e.amount);
      else if (e.direction === 'OUT') balance = r2(balance - e.amount);
      return { ...e, balance };
    });
    return { events: rows, balance };
  }

  /** Resolve + validate a holder (supplier / driver must be this tenant's). */
  async resolveHolder(h: CashHolder): Promise<ResolvedCashHolder> {
    const holder = cashHolderKey(h);
    if (holder.holder_type === 'SUPPLIER') {
      const rows = (await this.repo.manager.query(
        `SELECT d.id FROM drivers d
           JOIN suppliers s ON s.id = $2 AND s.tenant_id = $3 AND s.is_deleted = false
          WHERE d.id = $1 AND d.tenant_id = $3 AND d.is_deleted = false`,
        [holder.driver_id, holder.supplier_id, this.repo.currentTenantId()],
      )) as unknown[];
      if (!rows.length) throw new BadRequestException('Supplier or driver not found');
    }
    return holder;
  }

  /** B — cash given to / spent for a customer of a booking. */
  async customerUse(dto: CashHeldCustomerUseDto) {
    const holder = await this.resolveHolder(dto.holder);
    await this.requireBooking(dto.booking_id);
    const saved = await this.spend(holder, dto.currency_id, dto.amount, 'CUSTOMER_USE', {
      movement_date: dto.date,
      booking_id: dto.booking_id,
      notes: dto.notes.trim(),
    });
    return { id: saved.id, message: 'Cash used for customer recorded' };
  }

  /** C — paired TRANSFER_OUT / TRANSFER_IN between two holders. */
  async transfer(dto: CashHeldTransferDto) {
    const from = await this.resolveHolder(dto.holder);
    const to = await this.resolveHolder(dto.to_holder);
    if (from.holder_key === to.holder_key) {
      throw new BadRequestException('Choose a different holder to transfer to');
    }
    const id = await this.repo.manager.transaction(async (em) => {
      const out = await this.spendIn(em, from, dto.currency_id, dto.amount, 'TRANSFER_OUT', {
        movement_date: dto.date,
        notes: dto.notes?.trim() || null,
      });
      const inRow = await this.repo.insert(em, {
        ...to,
        movement_type: 'TRANSFER_IN',
        direction: 'IN',
        currency_id: dto.currency_id,
        amount: r2(dto.amount),
        movement_date: dto.date,
        related_movement_id: out.id,
        notes: dto.notes?.trim() || null,
      });
      await em
        .getRepository(CashHeldMovementEntity)
        .update({ id: out.id }, { related_movement_id: inRow.id });
      return out.id;
    });
    await this.audit.log('cash_held', id, 'transfer', [
      { field: 'amount', old_value: null, new_value: r2(dto.amount) },
      { field: 'to', old_value: from.holder_key, new_value: to.holder_key },
    ]);
    return { id, message: 'Cash transferred' };
  }

  /** D — cash returned to an office bank account. */
  async returnToOffice(dto: CashHeldReturnDto) {
    const holder = await this.resolveHolder(dto.holder);
    await this.bankAccounts.requireActive(dto.bank_account_id);
    const saved = await this.spend(holder, dto.currency_id, dto.amount, 'RETURNED', {
      movement_date: dto.date,
      bank_account_id: dto.bank_account_id,
      ref_no: dto.ref_no?.trim() || null,
      notes: dto.notes?.trim() || null,
    });
    return { id: saved.id, message: 'Cash returned to office recorded' };
  }

  /**
   * A — Pay Supplier "Paid from: cash held by …". Called by
   * PaymentSettlementService before writing the payout so an
   * over-spend fails with no payout created.
   */
  async assertCanPayFromHeld(h: CashHolder, currencyId: string, amount: number) {
    this.requireCashHeldEdit();
    const holder = await this.resolveHolder(h);
    const balance = await this.repo.balance(this.repo.manager, holder.holder_key, currencyId);
    if (r2(amount) > balance + 0.005) {
      throw new BadRequestException(
        `Not enough cash held — available ${balance.toFixed(2)}, needed ${r2(amount).toFixed(2)}`,
      );
    }
    return holder;
  }

  /** A — record the supplier payment against the holder (after the payout). */
  async recordSupplierPayment(
    h: CashHolder,
    currencyId: string,
    amount: number,
    date: string,
    payoutId: string,
    notes?: string | null,
  ) {
    const holder = await this.resolveHolder(h);
    return this.spend(holder, currencyId, amount, 'PAID_SUPPLIER', {
      movement_date: date,
      supplier_payout_id: payoutId,
      notes: notes?.trim() || null,
    });
  }

  private async spend(
    holder: ResolvedCashHolder,
    currencyId: string,
    amount: number,
    type: CashHeldMovementType,
    extra: Partial<CashHeldMovementEntity>,
  ) {
    const saved = await this.repo.manager.transaction((em) =>
      this.spendIn(em, holder, currencyId, amount, type, extra),
    );
    await this.audit.log('cash_held', saved.id, type.toLowerCase(), [
      { field: 'amount', old_value: null, new_value: r2(amount) },
      { field: 'holder', old_value: null, new_value: holder.holder_key },
    ]);
    return saved;
  }

  /** Lock the holder, check the balance, write the OUT movement. */
  private async spendIn(
    em: EntityManager,
    holder: ResolvedCashHolder,
    currencyId: string,
    amount: number,
    type: CashHeldMovementType,
    extra: Partial<CashHeldMovementEntity>,
  ) {
    const amt = r2(Number(amount));
    if (!(amt > 0)) throw new BadRequestException('Amount must be greater than 0');
    await this.repo.lockHolder(em, holder.holder_key);
    const balance = await this.repo.balance(em, holder.holder_key, currencyId);
    if (amt > balance + 0.005) {
      throw new BadRequestException(
        `Not enough cash held — available ${balance.toFixed(2)}, needed ${amt.toFixed(2)}`,
      );
    }
    return this.repo.insert(em, {
      ...holder,
      movement_type: type,
      direction: 'OUT',
      currency_id: currencyId,
      amount: amt,
      ...extra,
    });
  }

  private async requireBooking(bookingId: string) {
    const rows = (await this.repo.manager.query(
      `SELECT id FROM bookings WHERE id = $1 AND tenant_id = $2 AND is_deleted = false`,
      [bookingId, this.repo.currentTenantId()],
    )) as unknown[];
    if (!rows.length) throw new NotFoundException('Booking not found');
  }

  /** Paying a supplier from held cash also needs Cash Held → Edit. */
  private requireCashHeldEdit() {
    const perms = this.cls.get<Record<string, string> | null>(CLS_USER_PERMISSIONS) ?? {};
    if ((LEVEL[perms.cash_held] ?? 0) < LEVEL[AccessLevel.EDIT]) {
      throw new ForbiddenException('Cash Held → Edit is required to pay from held cash');
    }
  }
}
