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

/**
 * Raw analytics event — the canonical event log.
 *
 * The processor service is now the canonical writer: the ingest-writer inserts
 * rows here from edge envelopes, and the aggregation worker reads them back by
 * id. This must carry the full schema (including the cross-domain dimensions),
 * not just the read-side subset.
 */
@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;

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

  @Column({ type: 'varchar', length: 64 })
  @Index()
  sessionId!: string;

  @Column({ type: 'varchar', length: 64, nullable: true })
  @Index()
  userId?: string | null;

  @Column({ type: 'text', nullable: true })
  pageUrl?: string | null;

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

  @Column({ type: 'varchar', length: 20, nullable: true })
  deviceType?: string | null;

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

  @Column({ type: 'timestamptz' })
  @Index()
  timestamp!: Date;

  @CreateDateColumn({ type: 'timestamptz' })
  receivedAt!: Date;

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

  @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;
}
