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

/**
 * Tipo de regla de match para conciliacion automatica
 */
export type ReconciliationMatchType = 'exact_amount' | 'reference_contains' | 'partner_name';

/**
 * Entity: BankReconciliationRule
 * Reglas para conciliacion automatica de movimientos bancarios
 * Schema: financial
 * Table: bank_reconciliation_rules
 */
@Entity({ schema: 'financial', name: 'bank_reconciliation_rules' })
@Index('idx_bank_reconciliation_rules_tenant_id', ['tenantId'])
@Index('idx_bank_reconciliation_rules_company_id', ['companyId'])
@Index('idx_bank_reconciliation_rules_is_active', ['isActive'])
@Index('idx_bank_reconciliation_rules_match_type', ['matchType'])
@Index('idx_bank_reconciliation_rules_priority', ['priority'])
export class BankReconciliationRule {
  @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: 'varchar', length: 255, nullable: false })
  name: string;

  @Column({
    type: 'varchar',
    length: 50,
    nullable: false,
    name: 'match_type',
  })
  matchType: ReconciliationMatchType;

  @Column({ type: 'varchar', length: 255, nullable: false, name: 'match_value' })
  matchValue: string;

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

  @Column({
    type: 'boolean',
    default: true,
    nullable: false,
    name: 'is_active',
  })
  isActive: boolean;

  @Column({
    type: 'integer',
    default: 0,
    nullable: false,
  })
  priority: number;

  // Relations
  @ManyToOne(() => Account, { nullable: true })
  @JoinColumn({ name: 'auto_account_id' })
  autoAccount: Account | null;

  // 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;
}
