package userapi

import (
	"net/http"

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

type userHostIdentityData struct {
	IsHost       bool `json:"is_host"`
	IsAgent      bool `json:"is_agent"`
	IsManager    bool `json:"is_manager"`
	IsBD         bool `json:"is_bd"`
	IsBDLeader   bool `json:"is_bd_leader"`
	IsCoinSeller bool `json:"is_coin_seller"`
}

// getMyHostIdentity 聚合当前用户在 host domain 中的 App 端身份开关。
func (h *Handler) getMyHostIdentity(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.GetUserRoleSummary(request.Context(), &userv1.GetUserRoleSummaryRequest{
		Meta:   httpkit.UserMeta(request, ""),
		UserId: auth.UserIDFromContext(request.Context()),
	})
	if err != nil {
		httpkit.WriteRPCError(writer, request, err)
		return
	}

	summary := resp.GetSummary()
	httpkit.WriteOK(writer, request, userHostIdentityData{
		IsHost:       summary.GetIsHost(),
		IsAgent:      summary.GetIsAgency(),
		IsManager:    summary.GetIsManager(),
		IsBD:         summary.GetIsBd(),
		IsBDLeader:   summary.GetIsBdLeader(),
		IsCoinSeller: summary.GetIsCoinSeller(),
	})
}

// getMyRoleSummary 返回我的页入口显隐所需的完整角色摘要。
func (h *Handler) getMyRoleSummary(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.GetUserRoleSummary(request.Context(), &userv1.GetUserRoleSummaryRequest{
		Meta:   httpkit.UserMeta(request, ""),
		UserId: auth.UserIDFromContext(request.Context()),
	})
	if err != nil {
		httpkit.WriteRPCError(writer, request, err)
		return
	}
	summary := resp.GetSummary()
	httpkit.WriteOK(writer, request, overviewRolesData{
		IsHost:                 summary.GetIsHost(),
		IsAgency:               summary.GetIsAgency(),
		IsManager:              summary.GetIsManager(),
		IsBD:                   summary.GetIsBd(),
		IsBDLeader:             summary.GetIsBdLeader(),
		IsCoinSeller:           summary.GetIsCoinSeller(),
		HostStatus:             summary.GetHostStatus(),
		AgencyID:               summary.GetAgencyId(),
		BDID:                   summary.GetBdId(),
		BDStatus:               summary.GetBdStatus(),
		CoinSellerStatus:       summary.GetCoinSellerStatus(),
		PendingRoleInvitations: summary.GetPendingRoleInvitations(),
	})
}
