import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Stream, StreamStatus } from './entities/stream.entity';
import { YouTubeIntegrationService } from './youtube-integration.service';

@Injectable()
export class StreamHealthService {
  constructor(
    @InjectRepository(Stream)
    private readonly streamRepository: Repository<Stream>,
    private readonly youtubeService: YouTubeIntegrationService,
  ) {}

  async checkStreamHealth(streamId: string) {
    const stream = await this.streamRepository.findOne({ where: { id: streamId } });
    if (!stream || !stream.youtubeVideoId) return null;

    const health = await this.youtubeService.getLiveStreamHealth(streamId);
    
    // Auto-update stream status based on YouTube data
    if (health.isLive && stream.status !== StreamStatus.LIVE) {
      await this.streamRepository.update(streamId, {
        status: StreamStatus.LIVE,
        actualStartTime: new Date(),
      });
    } else if (!health.isLive && stream.status === StreamStatus.LIVE) {
      await this.streamRepository.update(streamId, {
        status: StreamStatus.ENDED,
        endedAt: new Date(),
      });
    }

    return {
      streamId,
      status: health.isLive ? 'live' : 'offline',
      viewers: health.viewers,
      title: health.title,
    };
  }
}