package rest

import (
	"encoding/json"
	"net/http"

	"github.com/explorer/backend/featureflags"
)

// handleFeatures handles GET /api/v1/features
// Returns available features for the current user based on their track level
func (s *Server) handleFeatures(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		writeError(w, http.StatusMethodNotAllowed, "method_not_allowed", "Method not allowed")
		return
	}

	// Extract user track from context (set by auth middleware)
	// Default to Track 1 (public) if not authenticated
	userTrack := 1
	if track, ok := r.Context().Value("user_track").(int); ok {
		userTrack = track
	}

	// Get enabled features for this track
	enabledFeatures := featureflags.GetEnabledFeatures(userTrack)

	// Get permissions based on track
	permissions := getPermissionsForTrack(userTrack)

	response := map[string]interface{}{
		"track":       userTrack,
		"features":    enabledFeatures,
		"permissions": permissions,
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(response)
}

// getPermissionsForTrack returns permissions for a given track level
func getPermissionsForTrack(track int) []string {
	permissions := []string{
		"explorer.read.blocks",
		"explorer.read.transactions",
		"explorer.read.address.basic",
		"explorer.read.bridge.status",
		"weth.wrap",
		"weth.unwrap",
	}

	if track >= 2 {
		permissions = append(permissions,
			"explorer.read.address.full",
			"explorer.read.tokens",
			"explorer.read.tx_history",
			"explorer.read.internal_txs",
			"explorer.search.enhanced",
		)
	}

	if track >= 3 {
		permissions = append(permissions,
			"analytics.read.flows",
			"analytics.read.bridge",
			"analytics.read.token_distribution",
			"analytics.read.address_risk",
		)
	}

	if track >= 4 {
		permissions = append(permissions,
			"operator.read.bridge_events",
			"operator.read.validators",
			"operator.read.contracts",
			"operator.read.protocol_state",
			"operator.write.bridge_control",
		)
	}

	return permissions
}
