package client

import (
	"context"

	"google.golang.org/grpc"
	userv1 "hyapp.local/api/proto/user/v1"
	"hyapp/pkg/appcode"
	domain "hyapp/services/activity-service/internal/domain/agencyopening"
)

// GRPCAgencyOpeningSource reads current Agency facts from user-service for activity qualification and scoring.
type GRPCAgencyOpeningSource struct {
	client userv1.UserHostServiceClient
}

func NewGRPCAgencyOpeningSource(conn *grpc.ClientConn) *GRPCAgencyOpeningSource {
	return &GRPCAgencyOpeningSource{client: userv1.NewUserHostServiceClient(conn)}
}

func (s *GRPCAgencyOpeningSource) ResolveOwnerAgency(ctx context.Context, userID int64) (domain.AgencySnapshot, bool, error) {
	summaryResp, err := s.client.GetUserRoleSummary(ctx, &userv1.GetUserRoleSummaryRequest{
		Meta:   meta(ctx, "agency-opening-owner"),
		UserId: userID,
	})
	if err != nil {
		return domain.AgencySnapshot{}, false, err
	}
	summary := summaryResp.GetSummary()
	if summary == nil || !summary.GetIsAgency() || summary.GetAgencyId() <= 0 {
		return domain.AgencySnapshot{}, false, nil
	}
	agencyResp, err := s.client.GetAgency(ctx, &userv1.GetAgencyRequest{
		Meta:     meta(ctx, "agency-opening-agency"),
		AgencyId: summary.GetAgencyId(),
	})
	if err != nil {
		return domain.AgencySnapshot{}, false, err
	}
	agency := agencyResp.GetAgency()
	if agency == nil || agency.GetOwnerUserId() != userID {
		return domain.AgencySnapshot{}, false, nil
	}
	snapshot := agencySnapshotFromProto(agency)
	membersResp, err := s.client.GetAgencyMembers(ctx, &userv1.GetAgencyMembersRequest{
		Meta:     meta(ctx, "agency-opening-agency-members"),
		AgencyId: snapshot.AgencyID,
		Status:   "active",
	})
	if err != nil {
		return domain.AgencySnapshot{}, false, err
	}
	// GetAgency 的基础事实不总是携带聚合人数；资格判断必须使用当前 active membership 事实，避免把有效 agency 误判成 0 主播。
	snapshot.HostCount = int32(len(membersResp.GetMemberships()))
	return snapshot, true, nil
}

func agencySnapshotFromProto(agency *userv1.Agency) domain.AgencySnapshot {
	if agency == nil {
		return domain.AgencySnapshot{}
	}
	return domain.AgencySnapshot{
		AgencyID:          agency.GetAgencyId(),
		RegionID:          agency.GetRegionId(),
		OwnerUserID:       agency.GetOwnerUserId(),
		Name:              agency.GetName(),
		Status:            agency.GetStatus(),
		HostCount:         agency.GetHostCount(),
		AgencyCreatedAtMS: agency.GetCreatedAtMs(),
	}
}

func meta(ctx context.Context, requestID string) *userv1.RequestMeta {
	return &userv1.RequestMeta{
		RequestId: requestID,
		Caller:    "activity-service",
		AppCode:   appcode.FromContext(ctx),
	}
}
