import { Entity, PrimaryGeneratedColumn, Column, Index, CreateDateColumn } from 'typeorm';
import { ZoomLiveEventType } from '../enum/zoom-live-event-type.enum';

/**
 * Append-only event log of live Zoom webinar join/leave observations — new,
 * standalone table for the Zoom live-tracking feature. One row per observed
 * event (a join webhook, a leave webhook, or a Dashboard-API self-healing
 * correction) — never updated or deleted. "Currently joined," "rejoin count,"
 * etc. are derived by querying this table (see
 * ZoomWebinarAnalyticsProvider.getLiveStatus), not stored as columns here.
 */
@Entity('zoom_analytics_live_event')
export class ZoomAnalyticsLiveEvent {
  @PrimaryGeneratedColumn('increment', { type: 'bigint' })
  id: number;

  @Index()
  @Column({ name: 'program_id', type: 'int' })
  programId: number;

  @Column({ name: 'session_id', type: 'int' })
  sessionId: number;

  @Index()
  @Column({ name: 'online_session_id', type: 'bigint' })
  onlineSessionId: number;

  @Index()
  @Column({ name: 'webinar_ext_id', type: 'varchar', length: 255 })
  webinarExtId: string;

  @Index()
  @Column({ name: 'email', type: 'varchar', length: 255 })
  email: string;

  /** Resolved by matching `email` against the panelist roster at write time; null if unmatched (e.g. a non-panelist join). */
  @Column({ name: 'user_id', type: 'int', nullable: true })
  userId: number | null;

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

  /** When Zoom reports the join/leave happened, or "now" for a Dashboard-poll correction. */
  @Column({ name: 'occurred_at', type: 'timestamptz' })
  occurredAt: Date;

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

  /** The display name Zoom reported for this join/leave (webhook's `participant.user_name`) — null for a Dashboard-poll correction, which carries no name. */
  @Column({ name: 'zoom_display_name', type: 'varchar', length: 255, nullable: true })
  zoomDisplayName: string | null;

  /** Zoom's reported reason a LEFT event happened (webhook's `participant.leave_reason`) — null for joins and corrections. */
  @Column({ name: 'leave_reason', type: 'varchar', length: 512, nullable: true })
  leaveReason: string | null;

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

  constructor(partial?: Partial<ZoomAnalyticsLiveEvent>) {
    Object.assign(this, partial ?? {});
  }
}
