package middleware

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"
	"time"

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

var secretKey = []byte("secret-key")

// AuthMiddleware protège les routes via JWT et redirige vers /login si non authentifié
func AuthMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ctx, ok := RedirectToLoginIfUnauthenticated(w, r)
		if !ok {
			return
		}
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}

// RedirectToLoginIfUnauthenticated vérifie le JWT et injecte ssoid dans le contexte, sinon redirige vers /login
func RedirectToLoginIfUnauthenticated(w http.ResponseWriter, r *http.Request) (context.Context, bool) {
	var tokenString string

	if authHeader := r.Header.Get("Authorization"); strings.HasPrefix(authHeader, "Bearer ") {
		tokenString = strings.TrimPrefix(authHeader, "Bearer ")
	}
	if tokenString == "" {
		if cookie, err := r.Cookie("token"); err == nil {
			tokenString = cookie.Value
		}
	}
	if tokenString == "" && r.Method == http.MethodPost || r.Method == http.MethodPut {
		if strings.Contains(r.Header.Get("Content-Type"), "application/json") {
			bodyCopy, _ := io.ReadAll(r.Body)
			var bodyMap map[string]interface{}
			if err := json.Unmarshal(bodyCopy, &bodyMap); err == nil {
				if val, ok := bodyMap["token"].(string); ok {
					tokenString = val
					r.Body = io.NopCloser(bytes.NewReader(bodyCopy))
				}
			}
		}
	}
	if tokenString == "" {
		http.Redirect(w, r, "/login", http.StatusSeeOther)
		return nil, false
	}
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("méthode signature invalide")
		}
		return secretKey, nil
	})
	if err != nil || !token.Valid {
		http.Redirect(w, r, "/login", http.StatusSeeOther)
		return nil, false
	}
	claims, ok := token.Claims.(jwt.MapClaims)
	if !ok {
		http.Redirect(w, r, "/login", http.StatusSeeOther)
		return nil, false
	}
	if exp, ok := claims["exp"].(float64); ok {
		if time.Now().Unix() > int64(exp) {
			http.Redirect(w, r, "/login", http.StatusSeeOther)
			return nil, false
		}
	}
	ssoid, ok := claims["username"].(string)
	if !ok || ssoid == "" {
		http.Redirect(w, r, "/login", http.StatusSeeOther)
		return nil, false
	}
	ctx := context.WithValue(r.Context(), "ssoid", ssoid)
	return ctx, true
}
