package com.ffii.fpsms.modules.monitoring.web

import com.ffii.fpsms.modules.monitoring.service.PrinterMonitorService
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
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 java.time.LocalDate
import java.time.LocalDateTime
import java.time.format.DateTimeParseException

@RestController
@RequestMapping("/printer-monitor")
@ConditionalOnProperty(prefix = "fpsms.monitoring", name = ["enabled"], havingValue = "true")
class PrinterMonitorController(
    private val printerMonitorService: PrinterMonitorService,
) {

    @GetMapping("/status")
    fun status(): ResponseEntity<Map<String, Any>> {
        return ResponseEntity.ok(printerMonitorService.listStatus())
    }

    @PostMapping("/check")
    fun checkNow(): ResponseEntity<Map<String, Any>> {
        return ResponseEntity.ok(printerMonitorService.checkAllPrinters())
    }

    @GetMapping("/history")
    fun history(
        @RequestParam fromDateTime: String,
        @RequestParam toDateTime: String,
        @RequestParam(required = false) printerId: Long?,
    ): ResponseEntity<Any> {
        val from = parseDateTimeParam(fromDateTime, endOfDay = false)
            ?: return ResponseEntity.badRequest().body(mapOf("error" to "Invalid fromDateTime"))
        val to = parseDateTimeParam(toDateTime, endOfDay = true)
            ?: return ResponseEntity.badRequest().body(mapOf("error" to "Invalid toDateTime"))
        if (from.isAfter(to)) {
            return ResponseEntity.badRequest().body(mapOf("error" to "fromDateTime must be before toDateTime"))
        }
        return ResponseEntity.ok(printerMonitorService.listHistory(from, to, printerId))
    }

    private fun parseDateTimeParam(raw: String, endOfDay: Boolean): LocalDateTime? {
        val text = raw.trim()
        if (text.isEmpty()) return null
        return try {
            when {
                text.length <= 10 -> {
                    val d = LocalDate.parse(text.take(10))
                    if (endOfDay) d.atTime(23, 59, 59) else d.atStartOfDay()
                }
                else -> LocalDateTime.parse(text.replace(" ", "T").take(19))
            }
        } catch (_: DateTimeParseException) {
            null
        }
    }
}
