package handlers

import "net/http"

// Auth is the middleware that wraps handlers with authentication
func (h *Handlers) Auth(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// If auth is disabled
		if h.authConfig.Disabled {
			next(w, r)
			return
		}

		// If custom validator is provided
		if h.authConfig.Validator != nil {
			if h.authConfig.Validator(r) {
				next(w, r)
				return
			}
			http.Error(w, "Unauthorized", http.StatusUnauthorized)
			return
		}

		// Built-in auth logic (API key, basic auth)
		if h.validateBuiltinAuth(r) {
			next(w, r)
			return
		}

		w.Header().Set("WWW-Authenticate", `Basic realm="WhatsHooked"`)
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
	}
}

// validateBuiltinAuth checks API key or basic auth
func (h *Handlers) validateBuiltinAuth(r *http.Request) bool {
	// Check if any authentication is configured
	hasAuth := h.authConfig.APIKey != "" || h.authConfig.Username != "" || h.authConfig.Password != ""
	if !hasAuth {
		// No authentication configured, allow access
		return true
	}

	// Check for API key authentication (x-api-key header or Authorization bearer token)
	if h.authConfig.APIKey != "" {
		// Check x-api-key header
		apiKey := r.Header.Get("x-api-key")
		if apiKey == h.authConfig.APIKey {
			return true
		}

		// Check Authorization header for bearer token
		authHeader := r.Header.Get("Authorization")
		if len(authHeader) > 7 && authHeader[:7] == "Bearer " {
			token := authHeader[7:]
			if token == h.authConfig.APIKey {
				return true
			}
		}
	}

	// Check for username/password authentication (HTTP Basic Auth)
	if h.authConfig.Username != "" && h.authConfig.Password != "" {
		username, password, ok := r.BasicAuth()
		if ok && username == h.authConfig.Username && password == h.authConfig.Password {
			return true
		}
	}

	return false
}
