import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
} from 'typeorm';
import { JournalEntry } from './journal-entry.entity.js';
import { Account } from './account.entity.js';

@Entity({ schema: 'financial', name: 'journal_entry_lines' })
@Index('idx_journal_entry_lines_entry_id', ['entryId'])
@Index('idx_journal_entry_lines_account_id', ['accountId'])
@Index('idx_journal_entry_lines_tenant_id', ['tenantId'])
export class JournalEntryLine {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

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

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

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

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

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

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

  @Column({ type: 'varchar', length: 255, nullable: true })
  ref: string | null;

  // Relations
  @ManyToOne(() => JournalEntry, (entry) => entry.lines, {
    onDelete: 'CASCADE',
  })
  @JoinColumn({ name: 'entry_id' })
  entry: JournalEntry;

  @ManyToOne(() => Account)
  @JoinColumn({ name: 'account_id' })
  account: Account;

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