import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  ManyToOne,
  JoinColumn,
  Unique,
} from 'typeorm';
import { Payment } from './payment.entity.js';
import { Invoice } from './invoice.entity.js';

@Entity({ schema: 'financial', name: 'payment_invoice_allocations' })
@Unique('uq_payment_invoice_allocations_payment_invoice', ['paymentId', 'invoiceId'])
export class PaymentInvoiceAllocation {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ type: 'uuid', nullable: false, name: 'payment_id' })
  paymentId: string;

  @Column({ type: 'uuid', nullable: false, name: 'invoice_id' })
  invoiceId: string;

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

  @Column({ type: 'date', nullable: false, default: () => 'CURRENT_DATE', name: 'allocation_date' })
  allocationDate: Date;

  // Relations
  @ManyToOne(() => Payment, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'payment_id' })
  payment: Payment;

  @ManyToOne(() => Invoice, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'invoice_id' })
  invoice: Invoice;

  // Audit fields
  @CreateDateColumn({ name: 'created_at', type: 'timestamptz' })
  createdAt: Date;

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