package handlers

import (
	"net/http"

	"sms-receiver-go/auth"
	"sms-receiver-go/config"
	"sms-receiver-go/models"
)

// RequireAuth 要求登录的中间件
func RequireAuth(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		loggedIn, _ := auth.CheckLogin(w, r)
		if !loggedIn {
			return // CheckLogin 已经处理重定向
		}
		next(w, r)
	}
}

// RequireAPIAuth API 鉴权中间件
func RequireAPIAuth(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		cfg := config.Get()
		if cfg.Security.Enabled {
			loggedIn, _ := auth.IsLoggedIn(r)
			if !loggedIn {
				writeJSON(w, models.APIResponse{
					Success: false,
					Error:   "未授权",
				}, http.StatusUnauthorized)
				return
			}
		}
		next(w, r)
	}
}
