package walletapi

import (
	"net/http"
	"strconv"
	"strings"

	userv1 "hyapp.local/api/proto/user/v1"
	"hyapp/services/gateway-service/internal/auth"
	"hyapp/services/gateway-service/internal/transport/http/httpkit"
)

type coinSellerData struct {
	UserID                  string `json:"user_id"`
	DisplayUserID           string `json:"display_user_id"`
	Username                string `json:"username"`
	Avatar                  string `json:"avatar,omitempty"`
	CountryID               int64  `json:"country_id"`
	CountryCode             string `json:"country_code,omitempty"`
	CountryName             string `json:"country_name,omitempty"`
	CountryDisplayName      string `json:"country_display_name,omitempty"`
	RegionID                int64  `json:"region_id"`
	RegionCode              string `json:"region_code,omitempty"`
	RegionName              string `json:"region_name,omitempty"`
	Status                  string `json:"status"`
	MerchantAssetType       string `json:"merchant_asset_type"`
	CanManageSubCoinSellers bool   `json:"can_manage_sub_coin_sellers"`
	// WhatsApp 字段固定输出，空联系方式也保留空字符串，避免充值页逐项读取时出现 schema 漂移。
	WhatsappPhone string `json:"whatsapp_phone"`
	WhatsappURL   string `json:"whatsapp_url"`
	UpdatedAtMS   int64  `json:"updated_at_ms"`
}

// listCoinSellers 返回当前用户所在区域内所有启用币商。
// gateway 不接受 region_id 参数，避免客户端绕过 user-service 的当前区域边界。
func (h *Handler) listCoinSellers(writer http.ResponseWriter, request *http.Request) {
	if h.userHostClient == nil {
		httpkit.WriteError(writer, request, http.StatusBadGateway, httpkit.CodeUpstreamError, "upstream service error")
		return
	}

	resp, err := h.userHostClient.ListActiveCoinSellersInMyRegion(request.Context(), &userv1.ListActiveCoinSellersInMyRegionRequest{
		Meta:   httpkit.UserMeta(request, ""),
		UserId: auth.UserIDFromContext(request.Context()),
	})
	if err != nil {
		httpkit.WriteRPCError(writer, request, err)
		return
	}

	items := make([]coinSellerData, 0, len(resp.GetCoinSellers()))
	for _, item := range resp.GetCoinSellers() {
		items = append(items, coinSellerFromProto(item))
	}
	httpkit.WriteOK(writer, request, map[string]any{"items": items, "total": len(items)})
}

func coinSellerFromProto(item *userv1.CoinSellerListItem) coinSellerData {
	if item == nil {
		return coinSellerData{}
	}
	contactInfo := strings.TrimSpace(item.GetContactInfo())
	return coinSellerData{
		UserID:                  int64IDString(item.GetUserId()),
		DisplayUserID:           item.GetDisplayUserId(),
		Username:                item.GetUsername(),
		Avatar:                  item.GetAvatar(),
		CountryID:               item.GetCountryId(),
		CountryCode:             item.GetCountryCode(),
		CountryName:             item.GetCountryName(),
		CountryDisplayName:      item.GetCountryDisplayName(),
		RegionID:                item.GetRegionId(),
		RegionCode:              item.GetRegionCode(),
		RegionName:              item.GetRegionName(),
		Status:                  item.GetStatus(),
		MerchantAssetType:       item.GetMerchantAssetType(),
		CanManageSubCoinSellers: item.GetCanManageSubCoinSellers(),
		WhatsappPhone:           contactInfo,
		WhatsappURL:             coinSellerWhatsAppURL(contactInfo),
		UpdatedAtMS:             item.GetUpdatedAtMs(),
	}
}

func coinSellerWhatsAppURL(raw string) string {
	contact := strings.TrimSpace(raw)
	if contact == "" {
		return ""
	}
	lower := strings.ToLower(contact)
	for _, prefix := range []string{"https://wa.me/", "http://wa.me/", "whatsapp://", "https://api.whatsapp.com/", "http://api.whatsapp.com/"} {
		if strings.HasPrefix(lower, prefix) {
			return contact
		}
	}

	var digits strings.Builder
	for _, r := range contact {
		if r >= '0' && r <= '9' {
			digits.WriteRune(r)
		}
	}
	if digits.Len() == 0 {
		return ""
	}
	return "https://wa.me/" + digits.String()
}

func int64IDString(value int64) string {
	if value <= 0 {
		return ""
	}
	return strconv.FormatInt(value, 10)
}
