package space.nstart.pcp.slots_service.controller

import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import space.nstart.pcp.slots_service.dto.tgu.TguPlanDecision
import space.nstart.pcp.slots_service.service.BallisticsService
import space.nstart.pcp.slots_service.service.TguPlanningService
import java.time.LocalDateTime
import java.util.UUID

@Controller
class TguPlanningPageController {

    @GetMapping("/tgu-planning")
    fun tguPlanningPage(): String = "tgu-planning"
}

@RestController
@RequestMapping("/api/tgu-planning")
class TguPlanningRestController(
    private val tguPlanningService: TguPlanningService,
    private val ballisticsService: BallisticsService
) {

    @GetMapping("/platforms")
    fun platforms() = tguPlanningService.platforms()

    @GetMapping("/plans")
    fun plans(@RequestParam(defaultValue = "7") historyDays: Long) =
        tguPlanningService.plans(historyDays)

    @GetMapping("/spacecraft/{spacecraftId}/plans")
    fun spacecraftPlans(
        @PathVariable spacecraftId: String,
        @RequestParam(defaultValue = "7") historyDays: Long
    ) = tguPlanningService.spacecraftPlans(spacecraftId, historyDays)

    @PostMapping("/plans/{planId}/decision")
    fun sendDecision(
        @PathVariable planId: UUID,
        @RequestParam decision: TguPlanDecision,
        @RequestParam(required = false) reason: String?
    ) = tguPlanningService.sendDecision(planId, decision, reason)

    /** «Снять с учёта» терминально-негативный план (чтобы не красил индикатор КА). */
    @PostMapping("/plans/{planId}/dismiss")
    fun dismissPlan(@PathVariable planId: UUID) = tguPlanningService.dismissPlan(planId)

    /** «Вернуть на учёт» план. */
    @PostMapping("/plans/{planId}/restore")
    fun restorePlan(@PathVariable planId: UUID) = tguPlanningService.restorePlan(planId)

    /** ТЕСТ: подтвердить закладку плана (AWAITING_LAYIN → LAID_IN). */
    @PostMapping("/plans/{planId}/confirm-layin")
    fun confirmLayin(
        @PathVariable planId: UUID,
        @RequestParam(required = false) reason: String?
    ) = tguPlanningService.confirmLayin(planId, reason)

    @GetMapping("/spacecraft/{noradId}/flight-line")
    fun spacecraftFlightLine(
        @PathVariable noradId: Long,
        @RequestParam("time_start", required = false) timeStart: LocalDateTime?,
        @RequestParam("time_stop", required = false) timeStop: LocalDateTime?
    ) = ballisticsService.flightLine(noradId, timeStart, timeStop).collectList().block() ?: emptyList<Any>()
}
