package middleware

import (
	"context"
	"errors"
	"net/http"

	"codeberg.org/mapleopentech/monorepo/cloud/maplepress-backend/config/constants"
)

// TenantMiddleware extracts tenant ID from JWT session context and adds to context
// This middleware must be used after JWT middleware in the chain
func TenantMiddleware() func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			// Get tenant from JWT session context (set by JWT middleware)
			tenantID, ok := r.Context().Value(constants.SessionTenantID).(string)
			if !ok || tenantID == "" {
				http.Error(w, "tenant context required", http.StatusUnauthorized)
				return
			}

			// Add to context with constants.ContextKeyTenantID for handler access
			ctx := context.WithValue(r.Context(), constants.ContextKeyTenantID, tenantID)
			next.ServeHTTP(w, r.WithContext(ctx))
		})
	}
}

// GetTenantID retrieves tenant ID from context
func GetTenantID(ctx context.Context) (string, error) {
	tenantID, ok := ctx.Value(constants.ContextKeyTenantID).(string)
	if !ok || tenantID == "" {
		return "", errors.New("tenant_id not found in context")
	}
	return tenantID, nil
}
