import { Entity, Column, Index, ManyToOne, JoinColumn, CreateDateColumn } from 'typeorm';
import { CustomerCreditLedgerEntity } from './customer-credit-ledger.entity';
import { PaymentCollectionEntity } from './payment-collection.entity';
import { SettlementPaymentEntity } from './settlement-payment.entity';

/**
 * Append-only audit log for every CREDIT (excess parked in) and
 * DEBIT (credit drawn down against a new collection or payout) on
 * a customer_credit_ledger header.
 *
 * Direction is part of the row, not the sign of `amount` — amount
 * is always positive. `balance_after` is the running balance on the
 * parent ledger snapshot at write-time so a movement row is
 * self-readable without re-joining and recomputing.
 */
export enum CreditLedgerDirection {
  CREDIT = 'CREDIT',
  DEBIT = 'DEBIT',
}

@Entity('customer_credit_ledger_movements')
@Index(['tenant_id', 'ledger_id', 'created_at'])
export class CustomerCreditLedgerMovementEntity {
  @Column({ type: 'uuid', primary: true, default: () => 'gen_random_uuid()' })
  id: string;

  @Column({ type: 'uuid' })
  tenant_id: string;

  @ManyToOne(() => CustomerCreditLedgerEntity, (l) => l.movements, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'ledger_id' })
  ledger: CustomerCreditLedgerEntity;

  @Column({ type: 'uuid' })
  ledger_id: string;

  @Column({ type: 'varchar', length: 8 })
  direction: CreditLedgerDirection;

  @Column({ type: 'decimal', precision: 12, scale: 2 })
  amount: number;

  @Column({ type: 'decimal', precision: 12, scale: 2 })
  balance_after: number;

  @ManyToOne(() => PaymentCollectionEntity, { nullable: true })
  @JoinColumn({ name: 'collection_id' })
  collection: PaymentCollectionEntity | null;

  @Column({ type: 'uuid', nullable: true })
  collection_id: string | null;

  @ManyToOne(() => SettlementPaymentEntity, { nullable: true })
  @JoinColumn({ name: 'settlement_payment_id' })
  settlement_payment: SettlementPaymentEntity | null;

  @Column({ type: 'uuid', nullable: true })
  settlement_payment_id: string | null;

  /** Set on SUPPLIER-ledger movements — the Pay Supplier voucher that
   *  parked or drew down this prepayment. */
  @Column({ type: 'uuid', nullable: true })
  payout_id: string | null;

  @Column({ type: 'text', nullable: true })
  notes: string | null;

  @Column({ type: 'uuid', nullable: true })
  created_by: string | null;

  @CreateDateColumn({ type: 'timestamptz' })
  created_at: Date;
}
