LiveActivityService.kt

// EV Supervision Lite — built by Kevin Vavelin, Codetics
// https://codetics.fr
// Copyright (c) 2026 Kevin Vavelin, Codetics
// SPDX-License-Identifier: LicenseRef-Codetics-Attribution-1.0

package fr.codetics.ev_server.services.notifications

import fr.codetics.ev_server.core.AppPrincipal
import fr.codetics.ev_server.core.Database
import fr.codetics.ev_server.core.I18n
import fr.codetics.ev_server.core.NotFound
import fr.codetics.ev_server.core.ensure
import fr.codetics.ev_server.core.lock
import fr.codetics.ev_server.core.msg
import fr.codetics.ev_server.models.api.MutationResponse
import fr.codetics.ev_server.models.entities.LiveActivityEntity
import fr.codetics.ev_server.models.entities.LiveActivityLaunchEntity
import fr.codetics.ev_server.models.entities.LiveActivityStartTokenEntity
import fr.codetics.ev_server.models.entities.StationKey
import fr.codetics.ev_server.models.entities.TransactionEntity
import fr.codetics.ev_server.models.notifications.LiveActivityInput
import fr.codetics.ev_server.models.notifications.LiveActivityStartTokenInput
import fr.codetics.ev_server.models.sessions.ChargingSessionResponse
import fr.codetics.ev_server.ocpp.AuthorizationStatus
import fr.codetics.ev_server.repositories.LiveActivityLaunchRepository
import fr.codetics.ev_server.repositories.LiveActivityRepository
import fr.codetics.ev_server.repositories.LiveActivityStartTokenRepository
import fr.codetics.ev_server.repositories.StationRepository
import fr.codetics.ev_server.repositories.TransactionRepository
import fr.codetics.ev_server.services.sessions.ChargingSessionService
import java.time.Clock
import java.time.Duration
import java.time.Instant
import java.util.UUID
import org.springframework.data.domain.PageRequest
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Service
import tools.jackson.databind.ObjectMapper

/**
 * Drives the iOS Live Activity of a charging session from the server.
 *
 * - Start: when a session begins without the app (a badge at the station, the app closed), the server
 *   starts the activity with the device's push-to-start token. It waits a short grace period first,
 *   so a session started from the app keeps the activity the app created itself.
 * - Update: the app (or the system, after a push start) hands over the activity's own push token; the
 *   server pushes the session state at a steady pace and ends the activity once the session stops.
 */
@Service
class LiveActivityService(
    private val db: Database,
    private val activities: LiveActivityRepository,
    private val startTokens: LiveActivityStartTokenRepository,
    private val launches: LiveActivityLaunchRepository,
    private val transactions: TransactionRepository,
    private val stations: StationRepository,
    private val sessions: ChargingSessionService,
    private val gateways: List<LiveActivityGateway>,
    private val json: ObjectMapper,
    private val clock: Clock,
) {
    fun register(user: AppPrincipal, input: LiveActivityInput): MutationResponse {
        ensure(input.token.matches(TOKEN)) { msg("push.invalid_device") }
        ensure(input.environment in ENVIRONMENTS) { msg("push.unknown_environment") }
        val transaction = sessions.session(user, input.transactionId)
        if (transaction.userId != user.id) throw NotFound(msg("sessions.not_found"))
        ensure(transaction.stoppedAt == null) { msg("sessions.already_finished") }
        val token = input.token.lowercase()
        return db.atomic {
            val now = Instant.now(clock)
            val activity = activities.findById(token).orElse(null) ?: LiveActivityEntity(token = token, createdAt = now)
            activity.tenantId = user.tenantId
            activity.userId = user.id
            activity.transactionId = input.transactionId
            activity.environment = input.environment
            activity.pushedAt = null
            activity.attempts = 0
            activities.save(activity)
            MutationResponse()
        }
    }

    fun unregister(user: AppPrincipal, token: String): MutationResponse =
        db.atomic {
            activities.findById(token.lowercase()).orElse(null)
                ?.takeIf { it.userId == user.id }
                ?.let(activities::delete)
            MutationResponse()
        }

    fun registerStartToken(user: AppPrincipal, input: LiveActivityStartTokenInput): MutationResponse {
        ensure(input.token.matches(TOKEN)) { msg("push.invalid_device") }
        ensure(input.environment in ENVIRONMENTS) { msg("push.unknown_environment") }
        ensure(input.locale == null || input.locale.length <= 20) { msg("push.invalid_language") }
        val token = input.token.lowercase()
        return db.atomic {
            val now = Instant.now(clock)
            val entry = startTokens.findById(token).orElse(null) ?: LiveActivityStartTokenEntity(token = token, createdAt = now)
            entry.tenantId = user.tenantId
            entry.userId = user.id
            entry.environment = input.environment
            entry.locale = input.locale
            entry.updatedAt = now
            startTokens.save(entry)
            MutationResponse()
        }
    }

    fun unregisterStartToken(user: AppPrincipal, token: String): MutationResponse =
        db.atomic {
            startTokens.findById(token.lowercase()).orElse(null)
                ?.takeIf { it.userId == user.id }
                ?.let(startTokens::delete)
            MutationResponse()
        }

    @Scheduled(fixedDelay = 15000)
    fun publish() {
        val gateway = gateways.firstOrNull { it.configured } ?: return
        db.atomic {
            val now = Instant.now(clock)
            activities.deleteAllByCreatedAtBefore(now.minus(LIFETIME))
            launches.deleteAllByLaunchedAtBefore(now.minus(LIFETIME))
            launch(gateway, now)
            activities
                .findAllByOrderByCreatedAt(PageRequest.of(0, BATCH))
                .mapNotNull { db.lock<LiveActivityEntity>(it.token) }
                .forEach { publish(gateway, it, now) }
        }
    }

    private fun launch(gateway: LiveActivityGateway, now: Instant) {
        val devices = startTokens.findAllByOrderByUpdatedAt(PageRequest.of(0, BATCH)).groupBy { it.tenantId to it.userId }
        if (devices.isEmpty()) return
        val open = mutableMapOf<UUID, List<TransactionEntity>>()
        devices.forEach { (owner, tokens) ->
            val (tenant, user) = owner
            open.getOrPut(tenant) { transactions.findAllByTenantIdAndStoppedAtIsNull(tenant) }
                .filter { it.userId == user && it.authorizationStatus == AuthorizationStatus.Accepted }
                .filter { it.startedAt.isAfter(now.minus(LAUNCH_WINDOW)) && it.startedAt.isBefore(now.minus(LAUNCH_GRACE)) }
                .forEach { launch(gateway, it, tokens, now) }
        }
    }

    private fun launch(gateway: LiveActivityGateway, transaction: TransactionEntity, tokens: List<LiveActivityStartTokenEntity>, now: Instant) {
        val id = requireNotNull(transaction.id)
        val key = LiveActivityLaunchEntity.key(transaction.tenantId, id)
        if (launches.existsById(key)) return
        val launched = LiveActivityLaunchEntity(id = key, tenantId = transaction.tenantId, transactionId = id, launchedAt = now)
        if (activities.existsByTenantIdAndTransactionId(transaction.tenantId, id)) {
            launches.save(launched)
            return
        }
        val view = sessions.views(transaction.tenantId, listOf(transaction)).first()
        val station = stations.findById(StationKey(transaction.tenantId, transaction.stationId)).orElse(null)?.name ?: transaction.stationId
        val results =
            tokens.map { device ->
                val payload = I18n.with(device.locale) { startPayload(view, station, now) }
                gateway.sendLiveActivity(device.token, device.environment, payload, PRIORITY_HIGH).also {
                    if (it == PushResult.INVALID_DEVICE) startTokens.delete(device)
                }
            }
        if (results.any { it != PushResult.RETRY }) launches.save(launched)
    }

    private fun publish(gateway: LiveActivityGateway, activity: LiveActivityEntity, now: Instant) {
        val transaction = transactions.findByTenantIdAndId(activity.tenantId, activity.transactionId)
        if (transaction == null || transaction.userId != activity.userId) {
            activities.delete(activity)
            return
        }
        val finished = transaction.stoppedAt != null
        if (!finished && activity.pushedAt?.let { Duration.between(it, now) < INTERVAL } == true) return
        val view = sessions.views(activity.tenantId, listOf(transaction)).first()
        val result =
            gateway.sendLiveActivity(activity.token, activity.environment, payload(view, now), if (finished) PRIORITY_HIGH else PRIORITY_LOW)
        when {
            result == PushResult.INVALID_DEVICE -> activities.delete(activity)
            finished && result == PushResult.DELIVERED -> activities.delete(activity)
            result == PushResult.RETRY && ++activity.attempts >= MAXIMUM_ATTEMPTS -> activities.delete(activity)
            else -> {
                if (result == PushResult.DELIVERED) activity.attempts = 0
                activity.pushedAt = now
                activities.save(activity)
            }
        }
    }

    /** The content-state keys match `ChargingActivityAttributes.ContentState` in the iOS app. */
    private fun state(session: ChargingSessionResponse, now: Instant): Map<String, Any?> {
        val finished = session.stoppedAt != null
        return mapOf(
            "energyKwh" to session.energyKwh?.toDouble(),
            "powerKw" to if (finished) null else session.currentPowerKw?.toDouble(),
            "stateOfCharge" to session.stateOfCharge,
            "price" to session.price?.toDouble(),
            "currency" to session.currency,
            "durationSeconds" to session.durationSeconds,
            "finished" to finished,
            "stopReason" to session.stopReason,
            "updatedAt" to now.epochSecond.toDouble(),
        )
    }

    fun payload(session: ChargingSessionResponse, now: Instant): String {
        val finished = session.stoppedAt != null
        val aps =
            buildMap<String, Any?> {
                put("timestamp", now.epochSecond)
                put("event", if (finished) "end" else "update")
                put("content-state", state(session, now))
                if (finished) {
                    put("dismissal-date", now.plus(DISMISSAL).epochSecond)
                } else {
                    put("stale-date", now.plus(STALE).epochSecond)
                }
            }
        return json.writeValueAsString(mapOf("aps" to aps))
    }

    /** The attribute keys match `ChargingActivityAttributes` in the iOS app. A push start must carry an alert. */
    fun startPayload(session: ChargingSessionResponse, stationName: String, now: Instant): String {
        val aps =
            mapOf(
                "timestamp" to now.epochSecond,
                "event" to "start",
                "attributes-type" to ATTRIBUTES_TYPE,
                "attributes" to
                    mapOf(
                        "transactionId" to session.id,
                        "stationId" to session.stationId,
                        "stationName" to stationName,
                        "connectorId" to session.connectorId,
                        "startedAt" to session.startedAt.epochSecond.toDouble(),
                    ),
                "content-state" to state(session, now),
                "stale-date" to now.plus(STALE).epochSecond,
                "alert" to
                    mapOf(
                        "title" to msg("notification.session_started.subject"),
                        "body" to msg("live_activity.started.body", stationName, session.connectorId),
                    ),
            )
        return json.writeValueAsString(mapOf("aps" to aps))
    }

    private companion object {
        const val ATTRIBUTES_TYPE = "ChargingActivityAttributes"
        val TOKEN = Regex("[0-9a-fA-F]{32,400}")
        val ENVIRONMENTS = setOf("sandbox", "production")
        val INTERVAL: Duration = Duration.ofSeconds(60)
        val STALE: Duration = Duration.ofMinutes(10)
        val DISMISSAL: Duration = Duration.ofMinutes(30)
        val LIFETIME: Duration = Duration.ofHours(12)
        val LAUNCH_GRACE: Duration = Duration.ofSeconds(20)
        val LAUNCH_WINDOW: Duration = Duration.ofMinutes(15)
        const val PRIORITY_LOW = 5
        const val PRIORITY_HIGH = 10
        const val MAXIMUM_ATTEMPTS = 20
        const val BATCH = 200
    }
}