package controllers

import (
	"encoding/json"
	"net/http"

	"github.com/rede5/gohorsejobs/backend/internal/services"
)

type StorageController struct {
	storageService *services.StorageService
}

func NewStorageController(storageService *services.StorageService) *StorageController {
	return &StorageController{storageService: storageService}
}

// TestConnection verifies if the configured Object Storage is accessible
// @Summary      Test Object Storage Connection
// @Description  Checks if the current configuration (DB or Env) allows access to the S3 bucket.
// @Tags         admin
// @Accept       json
// @Produce      json
// @Success      200  {object}  map[string]string
// @Failure      500  {object}  map[string]string
// @Router       /admin/storage/test-connection [post]
func (c *StorageController) TestConnection(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	err := c.storageService.TestConnection(ctx)
	if err != nil {
		sendError(w, http.StatusInternalServerError, "Connection failed: "+err.Error())
		return
	}

	sendSuccess(w, map[string]string{"message": "Connection successful"})
}

func sendError(w http.ResponseWriter, code int, message string) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(code)
	json.NewEncoder(w).Encode(map[string]string{"error": message})
}

func sendSuccess(w http.ResponseWriter, data interface{}) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(data)
}
