package handler

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

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

// ─── Project Handlers ──────────────────────────────────────────────────────────

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

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

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