package handler

import (
	"log/slog"
	"net/http"
	"strings"

	"github.com/go-chi/chi/v5"

	"github.com/denisovdennis/autohero/internal/world"
)

type MapsHandler struct {
	world  *world.Service
	logger *slog.Logger
}

func NewMapsHandler(worldSvc *world.Service, logger *slog.Logger) *MapsHandler {
	return &MapsHandler{
		world:  worldSvc,
		logger: logger,
	}
}

// GetMap returns a deterministic server map with ETag support.
// GET /api/v1/maps/{mapId}
func (h *MapsHandler) GetMap(w http.ResponseWriter, r *http.Request) {
	mapID := chi.URLParam(r, "mapId")
	if strings.TrimSpace(mapID) == "" {
		writeJSON(w, http.StatusBadRequest, map[string]string{
			"error": "missing mapId",
		})
		return
	}

	serverMap, etag, ok := h.world.GetMap(mapID)
	if !ok {
		writeJSON(w, http.StatusNotFound, map[string]string{
			"error": "map not found",
		})
		return
	}

	ifNoneMatch := strings.TrimSpace(r.Header.Get("If-None-Match"))
	if ifNoneMatch != "" && ifNoneMatch == etag {
		w.Header().Set("ETag", etag)
		w.WriteHeader(http.StatusNotModified)
		return
	}

	w.Header().Set("ETag", etag)
	writeJSON(w, http.StatusOK, serverMap)
}
