package middleware

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

	"github.com/flowy-live/llink/internal/utils/flog"

	"github.com/flowy-live/llink/internal/auth"
)

type contextKey string

const (
	emailContextKey   contextKey = "email"
	humanIdContextKey contextKey = "humanId"
	isAdminContextKey contextKey = "isAdmin"
)

func WithEmail(ctx context.Context, email string) context.Context {
	return context.WithValue(ctx, emailContextKey, email)
}

func EmailFromContext(ctx context.Context) (string, bool) {
	email, ok := ctx.Value(emailContextKey).(string)
	return email, ok
}

func WithHumanId(ctx context.Context, humanId string) context.Context {
	return context.WithValue(ctx, humanIdContextKey, humanId)
}

func HumanIdFromContext(ctx context.Context) (string, bool) {
	humanId, ok := ctx.Value(humanIdContextKey).(string)
	return humanId, ok
}

func WithIsAdmin(ctx context.Context, isAdmin bool) context.Context {
	return context.WithValue(ctx, isAdminContextKey, isAdmin)
}

func IsAdminFromContext(ctx context.Context) bool {
	isAdmin, ok := ctx.Value(isAdminContextKey).(bool)
	return ok && isAdmin
}

// Auth validates the bearer session token and populates email/humanId/isAdmin
// into the request context for downstream handlers.
func Auth(authSvc auth.AuthService) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			token := extractBearerToken(r)
			if token == "" {
				http.Error(w, "unauthorized", http.StatusUnauthorized)
				return
			}

			session, err := authSvc.GetSession(r.Context(), token)
			if err != nil {
				http.Error(w, "unauthorized", http.StatusUnauthorized)
				return
			}

			if err := authSvc.ExtendSession(r.Context(), token); err != nil {
				flog.Warn("failed to extend session", "error", err)
			}

			ctx := WithEmail(r.Context(), session.Email)
			ctx = WithHumanId(ctx, session.HumanId)
			ctx = WithIsAdmin(ctx, authSvc.IsSystemAdmin(r.Context(), session.Email))
			next.ServeHTTP(w, r.WithContext(ctx))
		})
	}
}

func extractBearerToken(r *http.Request) string {
	authHeader := r.Header.Get("Authorization")
	if authHeader == "" {
		return ""
	}

	parts := strings.SplitN(authHeader, " ", 2)
	if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
		return ""
	}

	return parts[1]
}
