package server

import (
	"encoding/json"
	"net/http"

	"git.wntrmute.dev/kyle/mcr/internal/auth"
)

type adminErrorResponse struct {
	Error string `json:"error"`
}

func writeAdminError(w http.ResponseWriter, status int, message string) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	_ = json.NewEncoder(w).Encode(adminErrorResponse{Error: message})
}

func writeJSON(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	_ = json.NewEncoder(w).Encode(v)
}

// RequireAdmin returns middleware that checks for the admin role.
// Returns 403 with an admin error format if the caller is not an admin.
func RequireAdmin() func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			claims := auth.ClaimsFromContext(r.Context())
			if claims == nil {
				writeAdminError(w, http.StatusUnauthorized, "authentication required")
				return
			}
			if !hasRole(claims.Roles, "admin") {
				writeAdminError(w, http.StatusForbidden, "admin role required")
				return
			}
			next.ServeHTTP(w, r)
		})
	}
}

func hasRole(roles []string, target string) bool {
	for _, r := range roles {
		if r == target {
			return true
		}
	}
	return false
}
