package com.writeoff.module.system.controller;

import com.writeoff.common.api.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
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.time.format.DateTimeFormatter;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping({"/api/system", "/api"})
public class SystemController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Value("${spring.application.name:writeoff-backend}")
    private String applicationName;

    @Value("${app.runtime.version:${APP_VERSION:${project.version:0.0.1-SNAPSHOT}}}")
    private String applicationVersion;

    @Value("${app.runtime.build-time:${BUILD_TIME:unknown}}")
    private String buildTime;

    @GetMapping("/health")
    public ApiResponse<Map<String, Object>> health() {
        return ApiResponse.success(buildHealthPayload());
    }

    private Map<String, Object> buildHealthPayload() {
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("status", "UP");
        result.put("app", applicationName);
        result.put("timestamp", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        result.put("version", applicationVersion);
        result.put("buildTime", buildTime);
        result.put("stateStore", "MYSQL");

        try {
            jdbcTemplate.queryForObject("SELECT 1", Integer.class);
            result.put("database", "UP");
        } catch (Exception e) {
            result.put("database", "DOWN");
            result.put("databaseError", e.getMessage());
            result.put("status", "DEGRADED");
        }
        return result;
    }
}
