package middleware

import (
	"net/http"
	"strings"

	"qnc-server/app/main/model"
	jwtx "qnc-server/common/jwt"
	"qnc-server/common/result"
	"qnc-server/common/xerr"

	"github.com/zeromicro/go-zero/rest/httpx"
)

// 登录/注册等建立新会话的接口，不进行封禁检查（避免旧 token 导致误拦）
var authPathSuffixes = []string{
	"/user/auth",
	"/user/mobileCodeLogin",
	"/user/wxMiniAuth",
	"/user/wxh5Auth",
}

// UserDisableInterceptor 全局中间件：拦截封禁用户的请求
// 仅对携带 JWT 的前端用户请求进行封禁检查，管理员请求跳过
func UserDisableInterceptor(userModel model.UserModel, accessSecret string) func(next http.HandlerFunc) http.HandlerFunc {
	return func(next http.HandlerFunc) http.HandlerFunc {
		return func(w http.ResponseWriter, r *http.Request) {
			path := r.URL.Path
			for _, suffix := range authPathSuffixes {
				if path == suffix || strings.HasSuffix(path, suffix) {
					next(w, r)
					return
				}
			}

			authHeader := r.Header.Get("Authorization")
			if authHeader == "" {
				next(w, r)
				return
			}

			claims, err := jwtx.ParseJwtToken(authHeader, accessSecret)
			if err != nil {
				// JWT 解析失败交给下游 AuthInterceptor 处理
				next(w, r)
				return
			}

			// 管理员跳过封禁检查
			if claims.UserType == model.UserTypeAdmin {
				next(w, r)
				return
			}

			user, err := userModel.FindOne(r.Context(), claims.UserId)
			if err != nil {
				// 用户不存在，交给下游处理
				next(w, r)
				return
			}

			if user.Disable == 1 {
				httpx.WriteJson(w, http.StatusOK, result.Error(xerr.USER_DISABLED, xerr.MapErrMsg(xerr.USER_DISABLED)))
				return
			}

			next(w, r)
		}
	}
}
