import { Injectable, NotFoundException } from '@nestjs/common'; import { PrismaService } from '../../common/prisma.service'; @Injectable() export class LiveService { constructor(private prisma: PrismaService) {} async getTripLiveStatus(tripId: string) { const trip = await this.prisma.trip.findUnique({ where: { id: tripId }, include: { service: true, originStation: true, destinationStation: true, liveStatus: true, stopTimes: { include: { station: true }, orderBy: { sequence: 'asc' } } }, }); if (!trip) throw new NotFoundException('Trip not found'); const live = trip.liveStatus; const nextStop = trip.stopTimes.find((s) => s.status === 'UPCOMING' || s.status === 'APPROACHING'); return { tripId: trip.id, trainName: trip.service.name, fromStationName: trip.originStation.name, toStationName: trip.destinationStation.name, state: live?.state ?? trip.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 ?? trip.departureAt, }; } updateLiveStatus(tripId: string, data: any) { return this.prisma.tripLiveStatus.upsert({ where: { tripId }, update: data, create: { tripId, state: data.state ?? 'SCHEDULED', ...data } }); } getStopTimeline(tripId: string) { return this.prisma.tripStopTime.findMany({ where: { tripId }, 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' } }); } }