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'])
@Index(['visitorIdDaily', 'timestamp'])
@Index(['corpId', 'timestamp'])
@Index(['domainId', '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;

  /**
   * Daily-rotating visitor identity for cross-domain stitching.
   * sha256(daily_salt || ip || ua || lang). 32 bytes. Stable for the same
   * visitor across all our domains within a UTC day; unrecoverable after
   * salt rotation (cookie-free, GDPR-clean).
   */
  @Column({ type: 'bytea', nullable: true, name: 'visitor_id_daily' })
  visitorIdDaily?: Buffer | null;

  /** Corp that owns the originating domain. FK → corps(id). */
  @Column({ type: 'smallint', nullable: true, name: 'corp_id' })
  corpId?: number | null;

  /** Domain the event originated from. FK → domains(id). */
  @Column({ type: 'integer', nullable: true, name: 'domain_id' })
  domainId?: number | null;
}
