import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../../common/prisma.service';

@Injectable()
export class LiveService {
  constructor(private prisma: PrismaService) {}

  async getTripLiveStatus(scheduleId: string) {
    const schedule = await this.prisma.trainSchedule.findUnique({
      where: { id: scheduleId },
      include: { train: true, originStation: true, destinationStation: true, liveStatus: true, stopTimes: { include: { station: true }, orderBy: { sequence: 'asc' } } },
    });
    if (!schedule) throw new NotFoundException('Schedule not found');
    const live = schedule.liveStatus;
    const nextStop = schedule.stopTimes.find((s) => s.status === 'UPCOMING' || s.status === 'APPROACHING');
    return {
      scheduleId: schedule.id, trainName: schedule.train.name,
      fromStationName: schedule.originStation.name, toStationName: schedule.destinationStation.name,
      state: live?.state ?? schedule.status, currentLocationLabel: live?.currentLocationLabel,
      progressPercent: live?.progressPercent ?? 0, delayMinutes: live?.delayMinutes ?? 0,
      currentSpeedKph: live?.currentSpeedKph, platformLabel: live?.platformLabel,
      nextStopStationName: nextStop?.station.name, updatedAt: live?.updatedAt ?? schedule.departureAt,
    };
  }

  updateLiveStatus(scheduleId: string, data: any) {
    return this.prisma.tripLiveStatus.upsert({ where: { scheduleId }, update: data, create: { scheduleId, state: data.state ?? 'SCHEDULED', ...data } });
  }

  getStopTimeline(scheduleId: string) {
    return this.prisma.tripStopTime.findMany({ where: { scheduleId }, include: { station: true }, orderBy: { sequence: 'asc' } });
  }

  getStationCrowdSignals() { return this.prisma.stationCrowdSignal.findMany({ include: { station: true } }); }

  getWeatherAlerts() { return this.prisma.weatherAlert.findMany({ where: { validUntil: { gte: new Date() } }, orderBy: { createdAt: 'desc' } }); }
}
