package main

import (
	"context"
	"encoding/json"
	"net/http"
	"time"
)

// GET /api/nav?system=SYS-001&role=SUPER_ADMIN
func getNavMenuHandler(db *DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		systemID := r.URL.Query().Get("system")
		if systemID == "" {
			systemID = "SYS-001"
		}
		roleCode := r.URL.Query().Get("role")

		ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
		defer cancel()

		menu, err := db.GetNavMenu(ctx, systemID, roleCode)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
			return
		}

		if menu == nil {
			w.WriteHeader(http.StatusNotFound)
			json.NewEncoder(w).Encode(map[string]string{"error": "system not found"})
			return
		}

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

// GET /api/system-layers/{systemId}
func getSystemLayersHandler(db *DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		systemID := r.PathValue("systemId")
		if systemID == "" {
			systemID = "SYS-001"
		}

		ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
		defer cancel()

		layers, err := db.GetSystemLayers(ctx, systemID)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
			return
		}

		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(map[string]interface{}{
			"system_id": systemID,
			"layers":    layers,
		})
	}
}
