package middleware

import (
	"net/http"

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

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

// UserDisableInterceptorMiddleware 检查用户是否被封禁，封禁用户直接拦截并返回错误
type UserDisableInterceptorMiddleware struct {
	UserModel model.UserModel
}

// NewUserDisableInterceptorMiddleware 创建用户封禁检查中间件
func NewUserDisableInterceptorMiddleware(userModel model.UserModel) *UserDisableInterceptorMiddleware {
	return &UserDisableInterceptorMiddleware{
		UserModel: userModel,
	}
}

// Handle 处理请求：当用户已登录且被封禁时，直接返回错误
func (m *UserDisableInterceptorMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		claims, err := ctxdata.GetClaimsFromCtx(r.Context())
		if err != nil {
			// 无登录信息，放行（由后续认证中间件处理）
			next(w, r)
			return
		}

		// 管理员不检查 user 表的 disable 字段
		if claims.UserType == model.UserTypeAdmin {
			next(w, r)
			return
		}

		// 查询用户是否被封禁
		user, err := m.UserModel.FindOne(r.Context(), claims.UserId)
		if err != nil {
			// 用户不存在（如管理员账号）或查询失败，放行
			next(w, r)
			return
		}

		// 1 表示已禁用
		if user.Disable == 1 {
			errcode := xerr.USER_DISABLED
			errmsg := xerr.MapErrMsg(errcode)
			httpx.WriteJson(w, http.StatusOK, result.Error(errcode, errmsg))
			return
		}

		next(w, r)
	}
}
