package controllers

import (
	"net/http"

	"github.com/engigu/taskpool/internal/services"
	"github.com/gin-gonic/gin"
)

type InstallController struct {
	installService *services.InstallService
}

func NewInstallController() *InstallController {
	return &InstallController{
		installService: services.NewInstallService(),
	}
}

// GetInstallStatus 获取安装状态
// @Summary 获取安装状态
// @Description 检查系统是否已完成安装
// @Tags 安装
// @Produce json
// @Success 200 {object} services.InstallStatus
// @Router /api/v1/install/status [get]
func (c *InstallController) GetInstallStatus(ctx *gin.Context) {
	status, err := c.installService.CheckInstallStatus()
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	ctx.JSON(http.StatusOK, status)
}

// Install 执行安装
// @Summary 执行安装
// @Description 初始化系统配置和管理员账号
// @Tags 安装
// @Accept json
// @Produce json
// @Param request body services.InstallRequest true "安装请求"
// @Success 200 {object} map[string]interface{}
// @Failure 400 {object} map[string]string
// @Failure 500 {object} map[string]string
// @Router /api/v1/install [post]
func (c *InstallController) Install(ctx *gin.Context) {
	// 先检查是否已安装
	status, err := c.installService.CheckInstallStatus()
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "检查安装状态失败"})
		return
	}

	if status.Installed {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "系统已安装，无法重复安装"})
		return
	}

	var req services.InstallRequest
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "参数错误: " + err.Error()})
		return
	}

	// 验证必填字段
	if req.AdminUsername == "" {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "管理员用户名不能为空"})
		return
	}
	if req.AdminPassword == "" {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "管理员密码不能为空"})
		return
	}
	if len(req.AdminPassword) < 6 {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "管理员密码至少6位"})
		return
	}

	// MySQL 必填验证
	if req.DBType == "mysql" {
		if req.DBHost == "" {
			ctx.JSON(http.StatusBadRequest, gin.H{"error": "MySQL 主机不能为空"})
			return
		}
		if req.DBName == "" {
			ctx.JSON(http.StatusBadRequest, gin.H{"error": "MySQL 数据库名不能为空"})
			return
		}
	}

	// Redis 启用时的验证
	if req.RedisEnabled {
		if req.RedisHost == "" {
			ctx.JSON(http.StatusBadRequest, gin.H{"error": "Redis 主机不能为空"})
			return
		}
	}

	// 执行安装
	if err := c.installService.Install(&req); err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "安装失败: " + err.Error()})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"message":        "安装成功",
		"admin_username": req.AdminUsername,
	})
}
