package handler

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

	"github.com/saveinmed/backend-go/internal/domain"
)

// GetPaymentGatewayConfig returns the global config for a provider
func (h *Handler) GetPaymentGatewayConfig(w http.ResponseWriter, r *http.Request) {
	provider := r.PathValue("provider")
	cfg, err := h.svc.GetPaymentGatewayConfig(r.Context(), provider)
	if err != nil {
		http.Error(w, err.Error(), http.StatusNotFound)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	stdjson.NewEncoder(w).Encode(cfg)
}

// UpdatePaymentGatewayConfig updates or creates global gateway settings
func (h *Handler) UpdatePaymentGatewayConfig(w http.ResponseWriter, r *http.Request) {
	provider := r.PathValue("provider")
	var req struct {
		Active      bool    `json:"active"`
		Credentials string  `json:"credentials"` // Encrypted ideally, for MVP raw or simple encrypt
		Environment string  `json:"environment"`
		Commission  float64 `json:"commission"`
	}
	if err := stdjson.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	cfg := &domain.PaymentGatewayConfig{
		Provider:    provider,
		Active:      req.Active,
		Credentials: req.Credentials,
		Environment: req.Environment,
		Commission:  req.Commission,
	}

	if err := h.svc.UpsertPaymentGatewayConfig(r.Context(), cfg); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusOK)
}

// TestPaymentGateway simulates a connection check
func (h *Handler) TestPaymentGateway(w http.ResponseWriter, r *http.Request) {
	// Mock success for now
	w.WriteHeader(http.StatusOK)
	stdjson.NewEncoder(w).Encode(map[string]string{"status": "ok", "message": "Connection successful"})
}
