package handler

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

	"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/models"
)

// ─── Session Handlers ──────────────────────────────────────────────────────────

// ListSessions handles GET /api/sessions.
func (h *Handler) ListSessions(w http.ResponseWriter, r *http.Request) {
	sessions, err := h.Sessions.ListActive(r.Context())
	if err != nil {
		slog.Error("list sessions failed", "error", err)
		writeJSON(w, http.StatusInternalServerError, models.ErrorResponse{Error: "failed to list sessions"})
		return
	}
	if sessions == nil {
		sessions = []models.Session{}
	}

	page, pageSize := parsePagination(r)
	start, end := paginateSlice(len(sessions), page, pageSize)

	totalCount, _ := h.Sessions.Count(r.Context())
	writeJSON(w, http.StatusOK, models.PaginatedResponse{
		Data:       sessions[start:end],
		TotalCount: totalCount,
		Page:       page,
		PageSize:   pageSize,
		HasMore:    end < len(sessions),
	})
}
