import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
  Unique,
} from 'typeorm';
import { Branch } from './branch.entity';

export type TerminalProvider = 'clip' | 'mercadopago' | 'stripe';
export type HealthStatus = 'healthy' | 'degraded' | 'offline' | 'unknown';

@Entity({ name: 'branch_payment_terminals', schema: 'core' })
@Unique(['branchId', 'terminalProvider', 'terminalId'])
export class BranchPaymentTerminal {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Index()
  @Column({ name: 'branch_id', type: 'uuid' })
  branchId: string;

  // Terminal
  @Index()
  @Column({ name: 'terminal_provider', type: 'varchar', length: 30 })
  terminalProvider: TerminalProvider;

  @Column({ name: 'terminal_id', type: 'varchar', length: 100 })
  terminalId: string;

  @Column({ name: 'terminal_name', type: 'varchar', length: 100, nullable: true })
  terminalName: string;

  // Credenciales (encriptadas)
  @Column({ type: 'jsonb', default: {} })
  credentials: Record<string, any>;

  // Configuracion
  @Column({ name: 'is_primary', type: 'boolean', default: false })
  isPrimary: boolean;

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

  // Limites
  @Column({ name: 'daily_limit', type: 'decimal', precision: 12, scale: 2, nullable: true })
  dailyLimit: number;

  @Column({ name: 'transaction_limit', type: 'decimal', precision: 12, scale: 2, nullable: true })
  transactionLimit: number;

  // Ultima actividad
  @Column({ name: 'last_transaction_at', type: 'timestamptz', nullable: true })
  lastTransactionAt: Date;

  @Column({ name: 'last_health_check_at', type: 'timestamptz', nullable: true })
  lastHealthCheckAt: Date;

  @Column({ name: 'health_status', type: 'varchar', length: 20, default: 'unknown' })
  healthStatus: HealthStatus;

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

  @UpdateDateColumn({ name: 'updated_at', type: 'timestamptz' })
  updatedAt: Date;

  // Relaciones
  @ManyToOne(() => Branch, (branch) => branch.paymentTerminals, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'branch_id' })
  branch: Branch;
}
