import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
} from 'typeorm';
import { BankStatement } from './bank-statement.entity.js';
import { JournalEntryLine } from './journal-entry-line.entity.js';

/**
 * Entity: BankStatementLine
 * Lineas/movimientos del extracto bancario
 * Schema: financial
 * Table: bank_statement_lines
 */
@Entity({ schema: 'financial', name: 'bank_statement_lines' })
@Index('idx_bank_statement_lines_statement_id', ['statementId'])
@Index('idx_bank_statement_lines_tenant_id', ['tenantId'])
@Index('idx_bank_statement_lines_transaction_date', ['transactionDate'])
@Index('idx_bank_statement_lines_is_reconciled', ['isReconciled'])
@Index('idx_bank_statement_lines_reconciled_entry_id', ['reconciledEntryId'])
@Index('idx_bank_statement_lines_partner_id', ['partnerId'])
export class BankStatementLine {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

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

  @Column({ type: 'date', nullable: false, name: 'transaction_date' })
  transactionDate: Date;

  @Column({ type: 'date', nullable: true, name: 'value_date' })
  valueDate: Date | null;

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

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

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

  @Column({
    type: 'boolean',
    default: false,
    nullable: false,
    name: 'is_reconciled',
  })
  isReconciled: boolean;

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

  @Column({ type: 'timestamp with time zone', nullable: true, name: 'reconciled_at' })
  reconciledAt: Date | null;

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

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

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

  // Relations
  @ManyToOne(() => BankStatement, (statement) => statement.lines, {
    onDelete: 'CASCADE',
  })
  @JoinColumn({ name: 'statement_id' })
  statement: BankStatement;

  @ManyToOne(() => JournalEntryLine, { nullable: true })
  @JoinColumn({ name: 'reconciled_entry_id' })
  reconciledEntry: JournalEntryLine | null;

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