package handler

import (
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/gogenex/bridge-monitor/internal/monitor"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

func NewRouter(reconciler *monitor.BridgeMonitor, metrics *monitor.Metrics) *gin.Engine {
	r := gin.Default()

	v1 := r.Group("/v1/bridge")
	{
		v1.GET("/status", func(c *gin.Context) {
			result := reconciler.GetLatestResult()
			if result == nil {
				c.JSON(http.StatusOK, gin.H{"status": "no_data", "message": "No reconciliation performed yet"})
				return
			}
			c.JSON(http.StatusOK, gin.H{
				"status":      boolToStatus(result.Healthy),
				"tvl":         result.EthLocked,
				"ethLocked":   result.EthLocked,
				"genexMinted": result.GenexMinted,
				"discrepancy": result.Discrepancy,
				"lastCheck":   result.Timestamp,
			})
		})

		v1.GET("/reconciliation", func(c *gin.Context) {
			result := reconciler.GetLatestResult()
			if result == nil {
				c.JSON(http.StatusOK, gin.H{"message": "No reconciliation data"})
				return
			}
			c.JSON(http.StatusOK, result)
		})

		v1.GET("/history", func(c *gin.Context) {
			n, _ := strconv.Atoi(c.DefaultQuery("limit", "50"))
			history := reconciler.GetHistory(n)
			c.JSON(http.StatusOK, gin.H{"count": len(history), "results": history})
		})

		v1.POST("/pause", func(c *gin.Context) {
			// 紧急暂停（需要认证）
			c.JSON(http.StatusOK, gin.H{"status": "pause_requested", "message": "Emergency pause proposal created"})
		})
	}

	r.GET("/metrics", gin.WrapH(promhttp.Handler()))

	r.GET("/health", func(c *gin.Context) {
		result := reconciler.GetLatestResult()
		healthy := result == nil || result.Healthy
		c.JSON(http.StatusOK, gin.H{"status": boolToStatus(healthy)})
	})

	return r
}

func boolToStatus(healthy bool) string {
	if healthy {
		return "healthy"
	}
	return "unhealthy"
}
