package org.nstart.dep265.requestservice.service

import org.nstart.dep265.requestservice.entity.RequestEntity
import org.nstart.dep265.requestservice.entity.RequestStatus
import org.springframework.stereotype.Service
import java.time.LocalDateTime

@Service
class RequestLifecycleService(
    private val geometryService: GeometryService,
) {
    fun refreshStatus(request: RequestEntity, now: LocalDateTime): RequestLifecycleRefreshResult {
        if (request.status == RequestStatus.DELETED) {
            return RequestLifecycleRefreshResult(statusChanged = false, completedNow = false)
        }

        val previousStatus: RequestStatus = request.status
        val previousCompletedAt = request.completedAt

        val coveredPercent: Double = geometryService.coveredPercent(request.geometryArea, request.remainingArea)
        val requiredPercent = request.coverageRequiredPercent

        when {
            coveredPercent >= requiredPercent -> {
                request.status = RequestStatus.COMPLETED
                if (request.completedAt == null) {
                    request.completedAt = now
                }
            }
            now.isBefore(request.beginDateTime) -> {
                request.status = RequestStatus.ACCEPTED
                request.completedAt = null
            }
            now.isAfter(request.endDateTime) -> {
                request.status = RequestStatus.EXPIRED
                request.completedAt = null
            }
            else -> {
                request.status = RequestStatus.ACTIVE
                request.completedAt = null
            }
        }

        return RequestLifecycleRefreshResult(
            statusChanged = previousStatus != request.status || previousCompletedAt != request.completedAt,
            completedNow = previousStatus != RequestStatus.COMPLETED && request.status == RequestStatus.COMPLETED,
        )
    }
}

data class RequestLifecycleRefreshResult(
    val statusChanged: Boolean,

    val completedNow: Boolean,
)
