package auth

import (
	"context"
	"net/http"
	"strings"

	"github.com/golang-jwt/jwt/v5"
)

type AuthService interface {
	ValidateToken(tokenString string) (*jwt.Token, error)
	GetClientIDFromToken(token *jwt.Token) (string, error)
	GetClientUserIDFromToken(token *jwt.Token) (string, error)
}

var authService AuthService

func SetAuthService(service AuthService) {
	authService = service
}

func RequireAuth(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// Get token from Authorization header
		authHeader := r.Header.Get("Authorization")
		if authHeader == "" {
			http.Error(w, "Authorization header required", http.StatusUnauthorized)
			return
		}

		// Extract token from "Bearer <token>"
		parts := strings.Split(authHeader, " ")
		if len(parts) != 2 || parts[0] != "Bearer" {
			http.Error(w, "Invalid authorization header format", http.StatusUnauthorized)
			return
		}

		tokenString := parts[1]

		// Validate token
		token, err := authService.ValidateToken(tokenString)
		if err != nil {
			http.Error(w, "Invalid or expired token", http.StatusUnauthorized)
			return
		}

		// Get client_user_id and client_id from token
		clientUserID, err := authService.GetClientUserIDFromToken(token)
		if err != nil {
			http.Error(w, "Invalid token claims", http.StatusUnauthorized)
			return
		}

		clientID, err := authService.GetClientIDFromToken(token)
		if err != nil {
			http.Error(w, "Invalid token claims", http.StatusUnauthorized)
			return
		}

		// Add both client_user_id and client_id to context
		ctx := context.WithValue(r.Context(), "client_user_id", clientUserID)
		ctx = context.WithValue(ctx, "client_id", clientID)
		next.ServeHTTP(w, r.WithContext(ctx))
	}
}

