import {
  Column,
  CreateDateColumn,
  Entity,
  Index,
  JoinColumn,
  ManyToOne,
  PrimaryGeneratedColumn,
} from 'typeorm';
import { User } from '../../user/entities/user.entity';
import { Meeting } from './meeting.entity';

export enum ParticipantRole {
  AUDITOR = 'AUDITOR',
  CLIENT = 'CLIENT',
  OBSERVER = 'OBSERVER',
  HOST = 'HOST',
}

export enum JoinChannel {
  APP = 'APP',
  BROWSER = 'BROWSER',
  PHONE = 'PHONE',
}

/**
 * One row per join. Someone who drops and rejoins produces two rows, which is
 * correct — it is the honest record of who was present when.
 *
 * This IS the IAF MD 4 attendance evidence. Nobody types it.
 */
@Entity('meeting_participants')
@Index(['meeting_id', 'user_id'])
export class MeetingParticipant {
  @PrimaryGeneratedColumn()
  id: number;

  @Index()
  @Column({ type: 'int' })
  meeting_id: number;

  @ManyToOne(() => Meeting, (m) => m.participants, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'meeting_id' })
  meeting: Meeting;

  /**
   * Null for a guest who joined by invite link without a QRS account. The
   * display fields below are then the only record of who they were.
   */
  @Column({ type: 'int', nullable: true })
  user_id: number | null;

  @ManyToOne(() => User, { nullable: true, onDelete: 'SET NULL' })
  @JoinColumn({ name: 'user_id' })
  user: User | null;

  /** snapshot — survives the user being renamed or deleted */
  @Column({ type: 'varchar', length: 255 })
  display_name: string;

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

  @Column({
    type: 'enum',
    enum: ParticipantRole,
    default: ParticipantRole.OBSERVER,
  })
  role: ParticipantRole;

  @Column({
    type: 'enum',
    enum: JoinChannel,
    default: JoinChannel.APP,
  })
  channel: JoinChannel;

  @Column({ type: 'datetime' })
  joined_at: Date;

  @Column({ type: 'datetime', nullable: true })
  left_at: Date | null;

  @Column({ type: 'int', nullable: true })
  duration_seconds: number | null;

  /** set when they arrived through an invite link rather than the app */
  @Column({ type: 'int', nullable: true })
  invite_id: number | null;

  @CreateDateColumn()
  created_at: Date;
}
