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

/**
 * Raw analytics event - stores all incoming events before processing
 * Generic event schema - product-specific fields go in metadata
 */
@Entity('raw_events')
@Index(['sessionId', 'timestamp'])
@Index(['eventType', 'timestamp'])
@Index(['processed', 'timestamp'])
export class RawEvent {
  @PrimaryGeneratedColumn('uuid')
  id!: string;

  /**
   * Event type identifier
   * Generic: 'pageview', 'click', 'scroll', 'conversion', 'custom'
   * Product-specific types stored but processed by product-specific handlers
   */
  @Column({ type: 'varchar', length: 100 })
  @Index()
  eventType!: string;

  /** Session identifier (client-generated) */
  @Column({ type: 'varchar', length: 64 })
  @Index()
  sessionId!: string;

  /** Optional authenticated user ID */
  @Column({ type: 'varchar', length: 64, nullable: true })
  @Index()
  userId?: string | null;

  /** Page URL where event occurred */
  @Column({ type: 'text', nullable: true })
  pageUrl?: string | null;

  /** Referrer URL */
  @Column({ type: 'text', nullable: true })
  referrer?: string | null;

  /** Device type: 'desktop' | 'mobile' | 'tablet' | 'bot' */
  @Column({ type: 'varchar', length: 20, nullable: true })
  deviceType?: string | null;

  /** Event-specific data (JSON) */
  @Column({ type: 'jsonb', nullable: true })
  metadata?: Record<string, unknown> | null;

  /** Client-side timestamp (when event occurred) */
  @Column({ type: 'timestamptz' })
  @Index()
  timestamp!: Date;

  /** Server-side timestamp (when event received) */
  @CreateDateColumn({ type: 'timestamptz' })
  receivedAt!: Date;

  /** Whether event has been processed by aggregation workers */
  @Column({ type: 'boolean', default: false })
  @Index()
  processed!: boolean;

  /** Processing timestamp */
  @Column({ type: 'timestamptz', nullable: true })
  processedAt?: Date | null;
}
