package com.erp.task.controller;

import com.erp.task.monitor.TaskMonitor;
import com.erp.task.service.TaskExecutor;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.Status;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 健康检查接口
 */
@Tag(name = "健康检查", description = "系统健康状态监控")
@RestController
@RequestMapping("/actuator")
@RequiredArgsConstructor
public class HealthController {

    private final TaskMonitor taskMonitor;
    private final TaskExecutor taskExecutor;

    @Operation(summary = "健康检查")
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> health() {
        boolean healthy = taskMonitor.isHealthy();
        int runningCount = taskExecutor.getRunningCount();

        Map<String, Object> health = new HashMap<>();
        health.put("status", healthy ? Status.UP.getCode() : Status.DOWN.getCode());
        health.put("timestamp", LocalDateTime.now());
        health.put("components", Map.of(
                "taskScheduler", Map.of(
                        "status", Status.UP.getCode(),
                        "details", Map.of("runningTasks", runningCount)
                ),
                "taskMonitor", Map.of(
                        "status", healthy ? Status.UP.getCode() : Status.DOWN.getCode()
                )
        ));

        return ResponseEntity.ok(health);
    }

    @Operation(summary = "Prometheus指标")
    @GetMapping("/prometheus")
    public ResponseEntity<String> prometheus() {
        // 实际生产环境应配置micrometer-registry-prometheus自动暴露指标
        return ResponseEntity.ok("# Prometheus metrics endpoint\n# Configure prometheus metrics in application.properties");
    }

    @Operation(summary = "应用信息")
    @GetMapping("/info")
    public ResponseEntity<Map<String, Object>> info() {
        Map<String, Object> info = new HashMap<>();
        info.put("name", "scheduled-task-service");
        info.put("version", "1.0.0");
        info.put("description", "分布式定时任务调度服务");
        info.put("timestamp", LocalDateTime.now());
        return ResponseEntity.ok(info);
    }
}
