package api

import (
	"database/sql"
	"encoding/json"
	"errors"
	"net/http"
	"producer/internal/logging"
	"producer/internal/models"
)

// Errores predefinidos
var (
	ErrInvalidContentType = models.ApiError{
		Success: false,
		Status:  http.StatusUnsupportedMediaType,
		Message: "error",
		Data:    []models.DataItem{{Msg: "El Content-Type debe ser application/json"}},
	}

	ErrInvalidJSON = models.ApiError{
		Success: false,
		Status:  http.StatusBadRequest,
		Message: "error",
		Data:    []models.DataItem{{Msg: "Error al decodificar payload"}},
	}

	ErrJSONExtraContent = models.ApiError{
		Success: false,
		Status:  http.StatusBadRequest,
		Message: "error",
		Data:    []models.DataItem{{Msg: "El JSON contiene contenido extra después del objeto principal"}},
	}

	ErrMissingTransactionID = models.ApiError{
		Status:  http.StatusBadRequest,
		Success: false,
		Message: "error",
		Data:    []models.DataItem{{Msg: "Transaccion_id es requerido"}},
	}

	ErrInvalidUUID = models.ApiError{
		Success: false,
		Status:  http.StatusBadRequest,
		Message: "error",
		Data:    []models.DataItem{{Msg: "El ID proporcionado no es un UUID válido"}},
	}

	ErrFacturaNotFound = models.ApiError{
		Success: false,
		Status:  http.StatusNotFound,
		Message: "error",
		Data:    []models.DataItem{{Msg: "La factura solicitada no existe"}},
	}

	ErrKafkaPublish = models.ApiError{
		Success: false,
		Status:  http.StatusServiceUnavailable,
		Message: "error",
		Data:    []models.DataItem{{Msg: "Error al publicar un mensaje en Kafka"}},
	}

	ErrDatabaseQuery = models.ApiError{
		Success: false,
		Status:  http.StatusInternalServerError,
		Message: "error",
		Data:    []models.DataItem{{Msg: ""}},
	}

	ErrInternal = models.ApiError{
		Success: false,
		Status:  http.StatusInternalServerError,
		Message: "error",
		Data:    []models.DataItem{{Msg: "Ocurrio un error inesperado"}},
	}
)

func writeError(w http.ResponseWriter, err error) {
	var apiErr models.ApiError

	if errors.As(err, &apiErr) {
		// Ya es un ApiError
	} else if errors.Is(err, sql.ErrNoRows) {
		logging.ErrorLogger.Printf("La factura solicitada no existe")
		apiErr = ErrFacturaNotFound
	} else {
		// Error genérico, no exponemos detalles al cliente
		logging.ErrorLogger.Printf("Error interno del servidor: %v", err)
		apiErr = ErrInternal
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(apiErr.Status)

	if err := json.NewEncoder(w).Encode(apiErr); err != nil {
		logging.ErrorLogger.Printf("Error escribiendo respuesta JSON: %v", err)
	}
}
