package handlers

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

	"github.com/CubeCraft-Creations/Extrudex/backend/internal/dtos"
	"github.com/CubeCraft-Creations/Extrudex/backend/internal/repositories"
)

// UsageLogHandler handles HTTP requests for usage log operations.
type UsageLogHandler struct {
	repo *repositories.UsageLogRepository
}

// NewUsageLogHandler creates a UsageLogHandler with the given repository.
func NewUsageLogHandler(repo *repositories.UsageLogRepository) *UsageLogHandler {
	return &UsageLogHandler{repo: repo}
}

// List handles GET /api/usage-logs — returns paginated, filtered usage logs.
func (h *UsageLogHandler) List(w http.ResponseWriter, r *http.Request) {
	limit, offset := parsePagination(r)
	filter := repositories.UsageLogFilter{
		Limit:  limit,
		Offset: offset,
	}

	if sidStr := r.URL.Query().Get("spool_id"); sidStr != "" {
		sid, err := strconv.Atoi(sidStr)
		if err != nil {
			writeJSON(w, http.StatusBadRequest, dtos.ErrorResponse{
				Error: "invalid spool_id",
				Code:  http.StatusBadRequest,
			})
			return
		}
		filter.SpoolID = &sid
	}

	if jidStr := r.URL.Query().Get("job_id"); jidStr != "" {
		jid, err := strconv.Atoi(jidStr)
		if err != nil {
			writeJSON(w, http.StatusBadRequest, dtos.ErrorResponse{
				Error: "invalid job_id",
				Code:  http.StatusBadRequest,
			})
			return
		}
		filter.JobID = &jid
	}

	logs, total, err := h.repo.GetAll(r.Context(), filter)
	if err != nil {
		slog.Error("failed to list usage logs", "error", err)
		writeJSON(w, http.StatusInternalServerError, dtos.ErrorResponse{
			Error: "internal server error",
			Code:  http.StatusInternalServerError,
		})
		return
	}

	writeJSON(w, http.StatusOK, dtos.ListResponse{
		Data:   logs,
		Total:  total,
		Limit:  limit,
		Offset: offset,
	})
}
