package userapi

import (
	"net/http"

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

type hostCenterAgencyData struct {
	AgencyID string `json:"agency_id"`
	ShortID  string `json:"short_id"`
	Name     string `json:"name"`
	Avatar   string `json:"avatar,omitempty"`
}

func (h *Handler) getHostCenterAgency(writer http.ResponseWriter, request *http.Request) {
	profile, ok := h.resolveCurrentActiveHostProfile(writer, request)
	if !ok {
		return
	}
	if profile.GetCurrentAgencyId() <= 0 {
		httpkit.WriteOK(writer, request, map[string]any{"agency": nil})
		return
	}
	if h.userHostClient == nil {
		httpkit.WriteError(writer, request, http.StatusBadGateway, httpkit.CodeUpstreamError, "upstream service error")
		return
	}

	// 当前主播所属 agency 只能从 user-service 的 host_profile 快照读取，前端不能传任意 agency_id 查看。
	agencyResp, err := h.userHostClient.GetAgency(request.Context(), &userv1.GetAgencyRequest{
		Meta:     httpkit.UserMeta(request, ""),
		AgencyId: profile.GetCurrentAgencyId(),
	})
	if err != nil {
		httpkit.WriteRPCError(writer, request, err)
		return
	}
	agency := agencyResp.GetAgency()
	if agency == nil || agency.GetAgencyId() != profile.GetCurrentAgencyId() || agency.GetStatus() != agencyStatusActive {
		httpkit.WriteError(writer, request, http.StatusForbidden, httpkit.CodePermissionDenied, "permission denied")
		return
	}

	data := hostCenterAgencyData{
		AgencyID: int64String(agency.GetAgencyId()),
		ShortID:  int64String(agency.GetAgencyId()),
		Name:     agency.GetName(),
		Avatar:   agency.GetAvatar(),
	}
	if agency.GetOwnerUserId() > 0 {
		profiles, err := h.userProfiles(request, []int64{agency.GetOwnerUserId()})
		if err != nil {
			httpkit.WriteRPCError(writer, request, err)
			return
		}
		if owner, exists := profiles[agency.GetOwnerUserId()]; exists {
			if owner.DisplayUserID != "" {
				data.ShortID = owner.DisplayUserID
			}
			if owner.Avatar != "" {
				data.Avatar = owner.Avatar
			}
		}
	}

	httpkit.WriteOK(writer, request, map[string]any{"agency": data})
}
