package org.hzhub.erp.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import lombok.RequiredArgsConstructor;
import org.hzhub.erp.common.domain.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.util.HashMap;
import java.util.Map;

/**
 * ERP 连接测试控制器
 */
@SaIgnore
@RestController
@RequestMapping("/erp/test")
@RequiredArgsConstructor
public class ErpTestController {

    private static final Logger log = LoggerFactory.getLogger(ErpTestController.class);
    private final JdbcTemplate jdbcTemplate;

    /**
     * 测试 SQL Server 数据库连接
     */
    @GetMapping("/connection")
    public R<Map<String, String>> testConnection() {
        Map<String, String> result = new HashMap<>();
        try {
            String version = jdbcTemplate.queryForObject("SELECT @@VERSION", String.class);
            String dbName = jdbcTemplate.queryForObject("SELECT DB_NAME()", String.class);
            result.put("status", "connected");
            result.put("database", dbName != null ? dbName : "unknown");
            result.put("version", version != null ? version.substring(0, Math.min(150, version.length())) : "unknown");
            return R.ok("SQL Server 连接成功", result);
        } catch (Exception e) {
            log.error("SQL Server 连接失败", e);
            Throwable cause = e;
            while (cause.getCause() != null) {
                cause = cause.getCause();
            }
            result.put("status", "failed");
            result.put("error", e.getMessage());
            result.put("rootCause", cause.getClass().getName() + ": " + cause.getMessage());
            return R.fail("SQL Server 连接失败: " + e.getMessage(), result);
        }
    }

    /**
     * 健康检查
     */
    @GetMapping("/health")
    public R<String> health() {
        return R.ok("hzhub-erp is running");
    }
}
