package gateway

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

	"realtime-gateway/internal/channel"
)

type createChannelRequest struct {
	Label        string `json:"label"`
	DeliveryMode string `json:"deliveryMode"`
	TTLSeconds   int    `json:"ttlSeconds"`
}

func (s *Server) registerChannelRoutes(mux *http.ServeMux) {
	mux.HandleFunc("/api/channel/create", s.handleCreateChannel)
	mux.HandleFunc("/api/admin/channels", s.handleAdminChannels)
}

func (s *Server) handleCreateChannel(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		writeJSON(w, http.StatusMethodNotAllowed, map[string]any{
			"error": "method not allowed",
		})
		return
	}

	var request createChannelRequest
	if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]any{
			"error": "invalid json body",
		})
		return
	}

	created, err := s.channels.Create(channel.CreateRequest{
		Label:        request.Label,
		DeliveryMode: request.DeliveryMode,
		TTLSeconds:   request.TTLSeconds,
	})
	if err != nil {
		writeJSON(w, http.StatusInternalServerError, map[string]any{
			"error": err.Error(),
		})
		return
	}

	writeJSON(w, http.StatusOK, created)
}

func (s *Server) handleAdminChannels(w http.ResponseWriter, _ *http.Request) {
	items := s.channels.List()
	writeJSON(w, http.StatusOK, map[string]any{
		"items": items,
		"count": len(items),
	})
}
