package router

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"

	"infogenie-backend/internal/database"
	"infogenie-backend/internal/handler"
	"infogenie-backend/internal/middleware"
)

func Setup(r *gin.Engine) {
	r.Use(middleware.CORS())

	authH := handler.NewAuthHandler()
	userH := handler.NewUserHandler()
	aiH := handler.NewAIModelHandler()
	siteH := handler.NewSiteConfigHandler()
	aiRtH := handler.NewAIRuntimeHandler()

	r.GET("/", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"message":     "万象口袋 后端 API 服务运行中",
			"description": "提供AI模型应用接口，用户认证由萌芽账户认证中心提供",
			"version":     "3.2.0-go",
			"timestamp":   time.Now().Format(time.RFC3339),
			"endpoints": gin.H{
				"auth":       "/api/auth (via 萌芽认证中心)",
				"user":       "/api/user",
				"aimodelapp": "/api/aimodelapp",
				"site":       "/api/site",
				"admin_site": "/api/admin/site/*",
			},
		})
	})

	// 健康检查：实际检测数据库连接
	r.GET("/api/health", func(c *gin.Context) {
		dbStatus := "connected"
		if database.DB != nil {
			sqlDB, err := database.DB.DB()
			if err != nil || sqlDB.Ping() != nil {
				dbStatus = "disconnected"
			}
		} else {
			dbStatus = "not_initialized"
		}
		c.JSON(http.StatusOK, gin.H{
			"status":    "running",
			"database":  dbStatus,
			"timestamp": time.Now().Format(time.RFC3339),
		})
	})

	auth := r.Group("/api/auth")
	{
		auth.GET("/check", middleware.OptionalJWTAuth(), authH.Check)
	}

	user := r.Group("/api/user", middleware.JWTAuth())
	{
		user.GET("/profile", userH.GetProfile)
	}

	// 站点公开配置（无需登录）
	r.GET("/api/site/60s-disabled", siteH.Get60sDisabled)
	r.GET("/api/site/60s-source", siteH.Get60sSource)
	r.GET("/api/site/ai-model-disabled", siteH.GetAIModelDisabled)
	r.PUT("/api/admin/site/60s-disabled", siteH.Put60sDisabled)
	r.PUT("/api/admin/site/60s-source", siteH.Put60sSource)
	r.PUT("/api/admin/site/ai-model-disabled", siteH.PutAIModelDisabled)
	r.GET("/api/admin/site/ai-runtime", aiRtH.GetAIRuntime)
	r.PUT("/api/admin/site/ai-runtime", aiRtH.PutAIRuntime)

	ai := r.Group("/api/aimodelapp")
	{
		ai.POST("/chat", middleware.JWTAuth(), aiH.Chat)
		ai.POST("/name-analysis", middleware.JWTAuth(), aiH.NameAnalysis)
		ai.POST("/variable-naming", middleware.JWTAuth(), aiH.VariableNaming)
		ai.POST("/poetry", middleware.JWTAuth(), aiH.Poetry)
		ai.POST("/translation", middleware.JWTAuth(), aiH.Translation)
		ai.POST("/classical_conversion", middleware.JWTAuth(), aiH.ClassicalConversion)
		ai.POST("/expression-maker", middleware.JWTAuth(), aiH.ExpressionMaker)
		ai.POST("/linux-command", middleware.JWTAuth(), aiH.LinuxCommand)
		ai.POST("/markdown_formatting", middleware.JWTAuth(), aiH.MarkdownFormatting)
		ai.POST("/kinship-calculator", middleware.JWTAuth(), aiH.KinshipCalculator)
		// models 端点添加认证保护
		ai.GET("/models", middleware.JWTAuth(), aiH.GetModels)
	}
}
