package handler

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

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

// ─── Task Handlers ─────────────────────────────────────────────────────────────

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

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

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