package handlers

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

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

// PrintJobHandler handles HTTP requests for print job operations.
type PrintJobHandler struct {
	service *services.PrintJobService
}

// NewPrintJobHandler creates a PrintJobHandler with the given service.
func NewPrintJobHandler(service *services.PrintJobService) *PrintJobHandler {
	return &PrintJobHandler{service: service}
}

// List handles GET /api/print-jobs — returns paginated, filtered print jobs.
func (h *PrintJobHandler) List(w http.ResponseWriter, r *http.Request) {
	limit, offset := parsePagination(r)
	filter := repositories.PrintJobFilter{
		Status: r.URL.Query().Get("status"),
		Limit:  limit,
		Offset: offset,
	}

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

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

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