import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
} from 'typeorm';
import { TerminalProvider } from './tenant-terminal-config.entity';
import { TerminalPayment } from './terminal-payment.entity';

@Entity({ name: 'terminal_webhook_events', schema: 'payment_terminals' })
@Index(['provider', 'eventId'], { unique: true })
export class TerminalWebhookEvent {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

  @Index()
  @Column({
    type: 'enum',
    enum: ['mercadopago', 'clip', 'stripe_terminal'],
    enumName: 'terminal_provider',
  })
  provider: TerminalProvider;

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

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

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

  @Index()
  @Column({ name: 'external_id', type: 'varchar', length: 255, nullable: true })
  externalId: string | null;

  @Column({ type: 'jsonb' })
  payload: Record<string, any>;

  @Column({ type: 'jsonb', nullable: true })
  headers: Record<string, any> | null;

  @Column({ name: 'signature_valid', type: 'boolean', nullable: true })
  signatureValid: boolean | null;

  @Index()
  @Column({ type: 'boolean', default: false })
  processed: boolean;

  @Column({ name: 'processed_at', type: 'timestamptz', nullable: true })
  processedAt: Date | null;

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

  @Column({ name: 'retry_count', type: 'integer', default: 0 })
  retryCount: number;

  @Index()
  @Column({ name: 'idempotency_key', type: 'varchar', length: 255, nullable: true })
  idempotencyKey: string | null;

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

  // Relaciones
  @ManyToOne(() => TerminalPayment, { nullable: true })
  @JoinColumn({ name: 'payment_id' })
  payment?: TerminalPayment;
}
