package middleware

import (
	"errors"

	"hfb_sys/backend/internal/modules/auth"
	"hfb_sys/backend/pkg/response"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func RequireRealname(users *auth.UserRepository) gin.HandlerFunc {
	return func(c *gin.Context) {
		if users == nil {
			response.ServiceUnavailable(c, "数据库未连接")
			c.Abort()
			return
		}
		value, ok := c.Get(ContextUserID)
		if !ok {
			response.Unauthorized(c, "缺少用户上下文")
			c.Abort()
			return
		}
		user, err := users.FindByID(value.(uint64))
		if errors.Is(err, gorm.ErrRecordNotFound) {
			response.Unauthorized(c, "用户不存在")
			c.Abort()
			return
		}
		if err != nil {
			response.ServiceUnavailable(c, "用户查询失败")
			c.Abort()
			return
		}
		if user.RealnameStatus != "verified" {
			response.Error(c, 403, "realname_required", "请先完成实名认证")
			c.Abort()
			return
		}
		c.Next()
	}
}
