package host

import (
	"context"
	"strings"

	"hyapp/pkg/xerr"
)

const (
	CapabilityManagerCenter           = "manager_center"
	CapabilityManagerResourceGrant    = "manager_resource_grant"
	CapabilityManagerGrantAvatarFrame = "manager_grant_avatar_frame"
	CapabilityManagerGrantVehicle     = "manager_grant_vehicle"
	CapabilityManagerGrantBadge       = "manager_grant_badge"
	CapabilityManagerGrantVIP         = "manager_grant_vip"
	CapabilityManagerUpdateUserLevel  = "manager_update_user_level"
	CapabilityManagerAddBDLeader      = "manager_add_bd_leader"
	CapabilityManagerCrossRegion      = "manager_cross_region"
	// CapabilityManagerAddBDLeaderInRegion 兼容上一版 gateway，底层读取同一个通用跨区经理开关。
	CapabilityManagerAddBDLeaderInRegion = "manager_add_bd_leader_in_region"
	CapabilityManagerAddAdmin            = "manager_add_admin"
	CapabilityManagerAddSuperadmin       = "manager_add_superadmin"
	CapabilityManagerBlockUser           = "manager_block_user"
	CapabilityManagerTransferCountry     = "manager_transfer_user_country"
)

// CheckBusinessCapability 是 App/H5 业务入口的服务端身份边界。
// 经理中心只认 manager_profiles 中的 active 经理身份，不把客户端自报角色、Agency owner 或普通 BD 当作授权依据。
func (s *Service) CheckBusinessCapability(ctx context.Context, actorUserID int64, capability string) (bool, string, error) {
	if s.repository == nil {
		return false, "", xerr.New(xerr.Unavailable, "host repository is not configured")
	}
	if actorUserID <= 0 {
		return false, "", xerr.New(xerr.InvalidArgument, "actor_user_id is required")
	}
	capability = strings.ToLower(strings.TrimSpace(capability))
	switch capability {
	case CapabilityManagerCenter:
		ok, err := s.repository.HasActiveManagerProfile(ctx, actorUserID)
		if err != nil {
			return false, "", err
		}
		if !ok {
			return false, "active_manager_required", nil
		}
		return true, "", nil
	case CapabilityManagerResourceGrant,
		CapabilityManagerGrantAvatarFrame,
		CapabilityManagerGrantVehicle,
		CapabilityManagerGrantBadge,
		CapabilityManagerGrantVIP,
		CapabilityManagerUpdateUserLevel,
		CapabilityManagerAddBDLeader,
		CapabilityManagerCrossRegion,
		CapabilityManagerAddBDLeaderInRegion,
		CapabilityManagerAddAdmin,
		CapabilityManagerAddSuperadmin,
		CapabilityManagerBlockUser,
		CapabilityManagerTransferCountry:
		// 细分能力必须同时满足 active 经理身份和对应权限开关；这样 H5 被篡改后直调写接口也会被 user-service 拒绝。
		ok, err := s.repository.HasActiveManagerCapability(ctx, actorUserID, capability)
		if err != nil {
			return false, "", err
		}
		if !ok {
			return false, "manager_capability_required", nil
		}
		return true, "", nil
	default:
		return false, "", xerr.New(xerr.InvalidArgument, "business capability is invalid")
	}
}
