package handler

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

	"github.com/gofrs/uuid/v5"
)

// GetSellerPaymentConfig returns the seller's payment configuration
func (h *Handler) GetSellerPaymentConfig(w http.ResponseWriter, r *http.Request) {
	idStr := r.PathValue("id")
	sellerID, err := uuid.FromString(idStr)
	if err != nil {
		http.Error(w, "invalid seller id", http.StatusBadRequest)
		return
	}

	// Verify permissions (only seller or admin)
	usr, err := h.getUserFromContext(r.Context())
	if err != nil {
		http.Error(w, "unauthorized", http.StatusUnauthorized)
		return
	}
	if usr.CompanyID != sellerID && usr.Role != "Admin" {
		http.Error(w, "forbidden", http.StatusForbidden)
		return
	}

	acc, err := h.svc.GetSellerPaymentAccount(r.Context(), sellerID)
	if err != nil {
		// return empty if not found? or 404?
		// for UX, empty object is often better
		stdjson.NewEncoder(w).Encode(map[string]any{})
		return
	}

	w.Header().Set("Content-Type", "application/json")
	stdjson.NewEncoder(w).Encode(acc)
}

// OnboardSeller initiates the onboarding flow (e.g. Stripe Connect)
func (h *Handler) OnboardSeller(w http.ResponseWriter, r *http.Request) {
	idStr := r.PathValue("id")
	sellerID, err := uuid.FromString(idStr)
	if err != nil {
		http.Error(w, "invalid seller id", http.StatusBadRequest)
		return
	}

	usr, err := h.getUserFromContext(r.Context())
	if err != nil {
		http.Error(w, "unauthorized", http.StatusUnauthorized)
		return
	}
	if usr.CompanyID != sellerID && usr.Role != "Admin" {
		http.Error(w, "forbidden", http.StatusForbidden)
		return
	}

	var req struct {
		Gateway string `json:"gateway"`
	}
	if err := stdjson.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	link, err := h.svc.OnboardSeller(r.Context(), sellerID, req.Gateway)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	stdjson.NewEncoder(w).Encode(map[string]string{"onboarding_url": link})
}
