package handlers

import (
	"net/http"
	"time"
	
	"easydo-echo_win7/models"
	"easydo-echo_win7/services"
	"easydo-echo_win7/utils"
	
	"github.com/labstack/echo-contrib/session"
	"github.com/labstack/echo/v4"
)

func Add_auth_to_routes(e *echo.Echo) {
	// 公共API路由（不需要认证）
	authGroup := e.Group("/auth")
	authGroup.GET("/health", healthCheck)
	authGroup.GET("/code", generateCaptcha)
	authGroup.POST("/login", login)
	authGroup.POST("/logout", logout)
	
}

// HealthCheck 健康检查
func healthCheck(c echo.Context) error {
	return c.JSON(http.StatusOK, utils.SuccessResponse("服务运行正常"))
}

// Login 用户登录
func login(c echo.Context) error {
	req := new(models.UserLoginRequest)
	
	// 验证请求参数
	if err := c.Bind(req); err != nil {
		return c.JSON(http.StatusBadRequest, utils.ErrorResponse("请求参数错误", err.Error()))
	}
	username := req.Username
	password := req.Password
	captchaID := req.CaptchaID
	captchaCode := req.CaptchaCode
	
	// 验证必填字段
	if username == "" || password == "" || captchaID == "" || captchaCode == "" {
		return c.JSON(http.StatusBadRequest, utils.ErrorResponse("请填写完整信息", ""))
	}
	
	// 检查登录尝试
	if ok, msg := services.CheckLoginAttempts(username); !ok {
		return c.JSON(http.StatusBadRequest, utils.ErrorResponse(msg, ""))
	}

	// 验证验证码
	if !services.VerifyCaptcha(captchaID, captchaCode) {
		services.RecordLoginAttempt(username, false)
		return c.JSON(http.StatusBadRequest, utils.ErrorResponse("验证码错误或已失效", ""))
	}

	// 验证用户凭据
	user := new(models.SysUser) 

	user.Username = &username
	err := services.JdbcClient.GetJdbcModel(user)

	if err != nil || *user.ID == 0  || user.TenantId == nil {
		services.RecordLoginAttempt(username, false)
		return c.JSON(http.StatusBadRequest, utils.ErrorResponse("用户不存在", ""))
	}
	tenant := new(models.Tenant)
	tenant.ID = user.TenantId

	err = services.JdbcClient.GetJdbcModelById(tenant)
	if err != nil {
		return c.JSON(http.StatusBadRequest, utils.ErrorResponse("企业不存在", ""))
	}
	if tenant.Status == nil || *tenant.Status != models.Status_Enable {
		return c.JSON(http.StatusBadRequest, utils.ErrorResponse("企业已被禁用", ""))
	}
	user.Tenant = tenant

	// 验证密码
	if !user.CheckPassword(password) {
		services.RecordLoginAttempt(username, false)
		return c.JSON(http.StatusBadRequest, utils.ErrorResponse("用户名或密码错误", ""))
	}
	// 创建会话
	sess, _ := session.Get("auth_session", c)
	sess.Values["user_id"] = user.ID
	sess.Values["username"] = user.Username
	sess.Values["is_authenticated"] = true
	sess.Values["login_time"] = time.Now().Unix()
	
	if err := sess.Save(c.Request(), c.Response()); err != nil {
		return c.JSON(http.StatusBadRequest, utils.ErrorResponse("会话创建失败", err.Error()))
	}
	dept := new(models.SysDept)
	dept.ID = user.DeptId

	err = services.JdbcClient.GetJdbcModelById(dept)
	if err != nil {
		return c.JSON(http.StatusBadRequest, utils.ErrorResponse("用户所属部门不存在", ""))
	}
	user.Dept = dept

	paramMap :=  map[string]interface{}{
		"userId": user.ID,
	}
	p_result,_ := services.JdbcClient.GetJdbcList(paramMap,models.SysUsersRoles{})
	p_list := utils.ConvertInterface[[]models.SysUsersRoles](p_result)
	role_id_list :=utils.Map(p_list, func(user_role models.SysUsersRoles) int64 {
		return *user_role.RoleID
	})

	for k := range paramMap {
		delete(paramMap, k)
	}
	paramMap["idIn"] = role_id_list
	r_result,_ := services.JdbcClient.GetJdbcList(paramMap,models.SysRole{})
	role_list := utils.ConvertInterface[[]models.SysRole](r_result)
	user.RoleList = &role_list
	// 记录成功登录
	services.RecordLoginAttempt(username, true)

	// 返回成功响应
	return c.JSON(http.StatusOK, map[string]interface{}{
		"token":"-",
		"user": user,
		"session_expires": time.Now().Add(7 * 24 * time.Hour).Unix(),
	})
	
}

// Logout 用户登出
func logout(c echo.Context) error {
	sess, _ := session.Get("auth_session", c)
	
	// 清除会话
	sess.Options.MaxAge = -1
	sess.Values = make(map[interface{}]interface{})
	
	if err := sess.Save(c.Request(), c.Response()); err != nil {
		return c.JSON(http.StatusBadRequest, utils.ErrorResponse("登出失败", err.Error()))
	}
	
	return c.JSON(http.StatusOK, utils.SuccessResponse("登出成功"))
}
