package walletapi

import (
	"net/http"
	"strconv"

	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"`
	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{}
	}
	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(),
		UpdatedAtMS:        item.GetUpdatedAtMs(),
	}
}

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