package http_router

import (
	"git-molva.ru/Molva/molva-backend/services/api_gateway/internal/auth"
	"git-molva.ru/Molva/molva-backend/services/api_gateway/internal/auth/keycloak"
	"log/slog"
	"net/http"
	"strings"
	"time"

	"git-molva.ru/Molva/molva-backend/services/api_gateway/internal/config"
)

type Middleware struct {
	logger      *slog.Logger
	authManager auth.Manager
}

type ConfigMiddleware struct {
	logger      *slog.Logger
	keycloakCfg *config.Keycloak
}

func NewMiddleware(c *ConfigMiddleware) (*Middleware, error) {
	authManager, err := keycloak.New(&keycloak.Config{
		AuthServerAddr: c.keycloakCfg.BaseURL,
		Realm:          c.keycloakCfg.Realm,
		ClientId:       c.keycloakCfg.ClientId,
		ClientSecret:   c.keycloakCfg.ClientSecret,
	})
	if err != nil {
		return nil, err
	}

	return &Middleware{
		logger:      c.logger,
		authManager: authManager,
	}, nil
}

// loggingMiddleware middleware для логирования запросов
func (m *Middleware) loggingMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		start := time.Now()

		m.logger.Info("Started request", slog.String("method", req.Method), slog.String("url", req.URL.Path))

		next.ServeHTTP(w, req)

		m.logger.Info("Completed request",
			slog.String("path", req.URL.Path),
			slog.Duration("duration", time.Since(start)))

	})
}

// authMiddleware middleware для валидации и обновления токена при истечении
func (m *Middleware) authMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		token := strings.TrimPrefix(req.Header.Get("Authorization"), "Bearer ")

		ok, err := m.authManager.CheckTokenIsValid(req.Context(), token)
		if err != nil || !ok {
			http.Error(w, "", http.StatusUnauthorized)
			return
		}

		next.ServeHTTP(w, req)
	})
}
