package middleware

import (
	"net/http"

	"bdrp-server/app/main/model"
	"bdrp-server/common/ctxdata"
	"bdrp-server/common/result"
	"bdrp-server/common/xerr"

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

// 用户封禁状态：0 可用，1 禁用
const userDisableStatus = 1

type UserAuthInterceptorMiddleware struct {
	UserModel model.UserModel
}

func NewUserAuthInterceptorMiddleware(userModel model.UserModel) *UserAuthInterceptorMiddleware {
	return &UserAuthInterceptorMiddleware{UserModel: userModel}
}

func (m *UserAuthInterceptorMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		claims, err := ctxdata.GetClaimsFromCtx(r.Context())
		if err != nil {
			m.writeErrorResponse(w, http.StatusUnauthorized, errors.Wrapf(xerr.NewErrCode(ErrCodeUnauthorized), "token解析失败: %v", err))
			return
		}
		if claims.UserType == model.UserTypeTemp {
			m.writeErrorResponse(w, http.StatusUnauthorized, errors.Wrapf(xerr.NewErrCode(xerr.USER_NEED_BIND_MOBILE), "请先绑定手机号"))
			return
		}
		// 封禁校验：用户已被禁用则直接拒绝
		user, err := m.UserModel.FindOne(r.Context(), claims.UserId)
		if err != nil {
			m.writeErrorResponse(w, http.StatusUnauthorized, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取用户信息失败: %v", err))
			return
		}
		if user.Disable == userDisableStatus {
			m.writeErrorResponse(w, http.StatusForbidden, xerr.NewErrCode(xerr.USER_DISABLED))
			return
		}
		next(w, r)
	}
}

// writeErrorResponse 统一返回 code + msg，便于前端展示提示信息
func (m *UserAuthInterceptorMiddleware) writeErrorResponse(w http.ResponseWriter, statusCode int, err error) {
	errcode := xerr.SERVER_COMMON_ERROR
	errmsg := xerr.MapErrMsg(errcode)
	if e, ok := errors.Cause(err).(*xerr.CodeError); ok {
		errcode = e.GetErrCode()
		errmsg = e.GetErrMsg()
	}
	httpx.WriteJson(w, statusCode, result.Error(errcode, errmsg))
}
