package httpapi

import (
	"net/http"

	"git.azzamo.net/Michilis/Spanglish/photo-api/internal/auth"
)

// requireAdmin mirrors the backend's requireAuth(['admin','organizer']):
// 401 {"error":"Unauthorized"} without a valid token, 403
// {"error":"Forbidden"} for valid non-admin users.
func (s *Server) requireAdmin(next func(http.ResponseWriter, *http.Request, auth.User)) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		user, err := s.verifier.FromRequest(r)
		if err != nil {
			writeError(w, http.StatusUnauthorized, "Unauthorized")
			return
		}
		if !user.IsAdmin() {
			writeError(w, http.StatusForbidden, "Forbidden")
			return
		}
		next(w, r, user)
	}
}

// optionalUser returns the authenticated user or nil; an invalid token is
// treated as anonymous rather than an error, matching how public backend
// routes behave.
func (s *Server) optionalUser(r *http.Request) *auth.User {
	user, err := s.verifier.FromRequest(r)
	if err != nil {
		return nil
	}
	return &user
}
