package handlers

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

	"git.warky.dev/wdevs/whatshooked/pkg/whatsapp/businessapi"
)

// GetBusinessProfile retrieves the business profile for a Business API account.
// POST /api/business-profile  {"account_id"}
func (h *Handlers) GetBusinessProfile(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

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

	baClient, err := h.getBusinessAPIClient(req.AccountID)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	profile, err := baClient.GetBusinessProfile(r.Context())
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	writeJSON(w, profile)
}

// UpdateBusinessProfile updates the business profile for a Business API account.
// POST /api/business-profile/update  {"account_id","about","address","description","email","websites":[],"vertical"}
func (h *Handlers) UpdateBusinessProfile(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	var req struct {
		AccountID   string   `json:"account_id"`
		About       string   `json:"about,omitempty"`
		Address     string   `json:"address,omitempty"`
		Description string   `json:"description,omitempty"`
		Email       string   `json:"email,omitempty"`
		Websites    []string `json:"websites,omitempty"`
		Vertical    string   `json:"vertical,omitempty"`
	}
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	baClient, err := h.getBusinessAPIClient(req.AccountID)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	profile := businessapi.BusinessProfileUpdate{
		About:       req.About,
		Address:     req.Address,
		Description: req.Description,
		Email:       req.Email,
		Websites:    req.Websites,
		Vertical:    req.Vertical,
	}

	if err := baClient.UpdateBusinessProfile(r.Context(), profile); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	writeJSON(w, map[string]string{"status": "ok"})
}
