import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  Index,
} from 'typeorm';

/**
 * Transactional Outbox table entity.
 * Business services write events to this table within the SAME transaction as business data.
 * The OutboxRelay (or Debezium CDC) picks up pending events and publishes to Kafka.
 */
@Entity('outbox')
@Index('idx_outbox_status_created', ['status', 'createdAt'])
export class OutboxEvent {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ name: 'aggregate_type', length: 100 })
  aggregateType: string; // e.g. 'User', 'Coupon', 'Order', 'Trade'

  @Column({ name: 'aggregate_id', type: 'uuid' })
  aggregateId: string;

  @Column({ name: 'event_type', length: 100 })
  eventType: string; // e.g. 'user.registered', 'trade.matched'

  @Column({ length: 100 })
  topic: string; // Kafka topic name

  @Column({ name: 'partition_key', length: 100, nullable: true })
  partitionKey?: string; // Kafka partition key

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

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

  @Column({ length: 20, default: 'pending' })
  status: 'pending' | 'published' | 'failed';

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

  @Column({ name: 'max_retries', type: 'smallint', default: 5 })
  maxRetries: number;

  @Column({ name: 'published_at', type: 'timestamptz', nullable: true })
  publishedAt?: Date;

  @Column({ name: 'expires_at', type: 'timestamptz' })
  expiresAt: Date;

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