package handlers

import (
	"encoding/json"
	"net/http"
	"time"

	"sms-receiver-go/config"
	"sms-receiver-go/database"
)

// HealthCheck 健康检查端点
func HealthCheck(startTime time.Time) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		cfg := config.Get()
		db := database.GetDB()

		// 检查数据库连接
		dbStatus := "ok"
		if db == nil {
			dbStatus = "disconnected"
		} else if err := db.Ping(); err != nil {
			dbStatus = "error: " + err.Error()
		}

		// 获取基本统计
		var totalMessages int64
		if dbStatus == "ok" {
			db.QueryRow("SELECT COUNT(*) FROM sms_messages").Scan(&totalMessages)
		}

		response := map[string]interface{}{
			"status":         "ok",
			"app_name":       cfg.App.Name,
			"version":        cfg.App.Version,
			"database":       dbStatus,
			"total_messages": totalMessages,
			"uptime":         time.Since(startTime).String(),
		}

		// 如果数据库有问题，返回503
		statusCode := http.StatusOK
		if dbStatus != "ok" {
			response["status"] = "degraded"
			statusCode = http.StatusServiceUnavailable
		}

		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(statusCode)
		json.NewEncoder(w).Encode(response)
	}
}
