package middleware

import (
	"context"
	"net/http"
	"time"

	"github.com/niels/banking-app/backend/internal/domain"
	"github.com/niels/banking-app/backend/internal/respond"
	"github.com/niels/banking-app/backend/internal/security"
)

type claimsKey struct{}

func Authenticate(tokens *security.TokenManager) Middleware {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			rawToken, err := security.BearerToken(r.Header.Get("Authorization"))
			if err != nil {
				respond.Error(w, err)
				return
			}

			claims, err := tokens.Verify(rawToken)
			if err != nil {
				respond.Error(w, err)
				return
			}

			ctx := context.WithValue(r.Context(), claimsKey{}, claims)
			next.ServeHTTP(w, r.WithContext(ctx))
		})
	}
}

func RequireRole(role string) Middleware {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			claims, ok := CurrentClaims(r)
			if !ok {
				respond.Error(w, domain.ErrUnauthorized)
				return
			}
			if claims.Role != role {
				respond.Error(w, domain.ErrForbidden)
				return
			}
			next.ServeHTTP(w, r)
		})
	}
}

func RequireScope(scope string) Middleware {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			claims, ok := CurrentClaims(r)
			if !ok {
				respond.Error(w, domain.ErrUnauthorized)
				return
			}
			if !claims.HasScope(scope) {
				respond.Error(w, domain.ErrForbidden)
				return
			}
			next.ServeHTTP(w, r)
		})
	}
}

func RequireStepUp(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		claims, ok := CurrentClaims(r)
		if !ok {
			respond.Error(w, domain.ErrUnauthorized)
			return
		}
		if !claims.HasFreshStepUp(time.Now().UTC()) {
			respond.Error(w, domain.ErrStepUpRequired)
			return
		}
		next.ServeHTTP(w, r)
	})
}

func CurrentClaims(r *http.Request) (*security.Claims, bool) {
	claims, ok := r.Context().Value(claimsKey{}).(*security.Claims)
	return claims, ok
}
