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"`
	JoinedAtMS int64  `json:"joined_at_ms,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(),
	}
	// 加入时间来自当前 membership 事实，不使用 host 首次成为主播时间；主播换公会后两者语义不同。
	membersResp, err := h.userHostClient.GetAgencyMembers(request.Context(), &userv1.GetAgencyMembersRequest{
		Meta:     httpkit.UserMeta(request, ""),
		AgencyId: agency.GetAgencyId(),
		Status:   "active",
	})
	if err == nil {
		// 加入时间是新增展示字段；该补充查询失败时保留旧响应，不能让 Lalu 历史页面因非关键字段不可用而整体失败。
		for _, membership := range membersResp.GetMemberships() {
			if membership.GetMembershipId() == profile.GetCurrentMembershipId() && membership.GetHostUserId() == profile.GetUserId() {
				data.JoinedAtMS = membership.GetJoinedAtMs()
				break
			}
		}
	}
	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
			}
		}
	}

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