import { Injectable } from '@nestjs/common';

export interface RaisedHand {
  userId: number;
  username: string;
  type: 'normal' | 'question';
  raisedAt: Date;
  timeoutId?: NodeJS.Timeout;
}

@Injectable()
export class ClassroomService {
  private raisedHands: Map<number, RaisedHand> = new Map();
  private activeStudent: { userId: number; username: string } | null = null;

  raiseHand(userId: number, username: string, type: 'normal' | 'question', onTimeout: (userId: number) => void) {
    // Clear existing timeout if re-raising or changing type
    const existingHand = this.raisedHands.get(userId);
    if (existingHand) {
      clearTimeout(existingHand.timeoutId);
    }

    const timeoutId = setTimeout(() => {
      onTimeout(userId);
    }, 10 * 60 * 1000); // 10 minutes

    this.raisedHands.set(userId, {
      userId,
      username,
      type,
      raisedAt: new Date(),
      timeoutId,
    });
  }

  lowerHand(userId: number) {
    const hand = this.raisedHands.get(userId);
    if (hand) {
      clearTimeout(hand.timeoutId);
      this.raisedHands.delete(userId);
      return true;
    }
    return false;
  }

  lowerAllHands() {
    this.raisedHands.forEach((hand) => clearTimeout(hand.timeoutId));
    this.raisedHands.clear();
  }

  getRaisedHands() {
    // Return array without timeoutId (not serializable/needed for frontend)
    return Array.from(this.raisedHands.values()).map(({ timeoutId, ...rest }) => rest);
  }

  setActiveStudent(userId: number, username: string) {
    this.activeStudent = { userId, username };
    // Also lower the hand of the picked student
    this.lowerHand(userId);
  }

  clearActiveStudent() {
    this.activeStudent = null;
  }

  getActiveStudent() {
    return this.activeStudent;
  }

  pickRandomStudent(): { userId: number; username: string } | null {
    const hands = Array.from(this.raisedHands.values());
    if (hands.length === 0) return null;

    const randomIndex = Math.floor(Math.random() * hands.length);
    const selected = hands[randomIndex];
    
    this.setActiveStudent(selected.userId, selected.username);
    return { userId: selected.userId, username: selected.username };
  }
}
