import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
  OneToMany,
} from 'typeorm';
import { Account } from './account.entity.js';

/**
 * Estado del extracto bancario
 */
export type BankStatementStatus = 'draft' | 'reconciling' | 'reconciled';

/**
 * Entity: BankStatement
 * Extractos bancarios importados para conciliacion
 * Schema: financial
 * Table: bank_statements
 */
@Entity({ schema: 'financial', name: 'bank_statements' })
@Index('idx_bank_statements_tenant_id', ['tenantId'])
@Index('idx_bank_statements_company_id', ['companyId'])
@Index('idx_bank_statements_bank_account_id', ['bankAccountId'])
@Index('idx_bank_statements_statement_date', ['statementDate'])
@Index('idx_bank_statements_status', ['status'])
export class BankStatement {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

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

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

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

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

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

  @Column({
    type: 'varchar',
    length: 20,
    default: 'draft',
    nullable: false,
  })
  status: BankStatementStatus;

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

  @Column({ type: 'uuid', nullable: true, name: 'imported_by' })
  importedBy: 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;

  // Relations
  @ManyToOne(() => Account)
  @JoinColumn({ name: 'bank_account_id' })
  bankAccount: Account | null;

  @OneToMany('BankStatementLine', 'statement')
  lines: import('./bank-statement-line.entity.js').BankStatementLine[];

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

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

  @UpdateDateColumn({
    name: 'updated_at',
    type: 'timestamp with time zone',
    nullable: true,
  })
  updatedAt: Date | null;

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