package handlers

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

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

// writeJSON serializes v as JSON to the response writer with the given status code.
// Logs an error if encoding fails.
func writeJSON(w http.ResponseWriter, status int, v interface{}) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	if err := json.NewEncoder(w).Encode(v); err != nil {
		slog.Error("failed to encode JSON response", "error", err)
	}
}

// parsePagination reads limit and offset query parameters with defaults of 20 and 0.
func parsePagination(r *http.Request) (limit, offset int) {
	limit = 20
	offset = 0

	if l := r.URL.Query().Get("limit"); l != "" {
		if parsed, err := strconv.Atoi(l); err == nil && parsed > 0 {
			limit = parsed
		}
	}
	if o := r.URL.Query().Get("offset"); o != "" {
		if parsed, err := strconv.Atoi(o); err == nil && parsed >= 0 {
			offset = parsed
		}
	}
	return
}

// ValidateCreateFilamentRequest validates a CreateFilamentRequest DTO.
// Re-exports the service-layer validator for handler use.
func ValidateCreateFilamentRequest(req dtos.CreateFilamentRequest) error {
	return services.ValidateCreateFilamentRequest(req)
}

// ValidateUpdateFilamentRequest validates an UpdateFilamentRequest DTO.
// Re-exports the service-layer validator for handler use.
func ValidateUpdateFilamentRequest(req dtos.UpdateFilamentRequest) error {
	return services.ValidateUpdateFilamentRequest(req)
}
