package http

import (
	"net/http"

	"hyapp/pkg/tencentrtc"
	"hyapp/services/gateway-service/internal/appconfig"
	"hyapp/services/gateway-service/internal/auth"
	gatewayclient "hyapp/services/gateway-service/internal/client"
	"hyapp/services/gateway-service/internal/transport/http/activityapi"
	"hyapp/services/gateway-service/internal/transport/http/appapi"
	"hyapp/services/gateway-service/internal/transport/http/callbackapi"
	"hyapp/services/gateway-service/internal/transport/http/gameapi"
	"hyapp/services/gateway-service/internal/transport/http/httpkit"
	"hyapp/services/gateway-service/internal/transport/http/httproutes"
	"hyapp/services/gateway-service/internal/transport/http/managerapi"
	"hyapp/services/gateway-service/internal/transport/http/messageapi"
	"hyapp/services/gateway-service/internal/transport/http/resourceapi"
	"hyapp/services/gateway-service/internal/transport/http/roomapi"
	"hyapp/services/gateway-service/internal/transport/http/userapi"
	"hyapp/services/gateway-service/internal/transport/http/walletapi"
)

// Routes 把 Handler 的私有方法适配成独立路由包需要的显式 handler 表。
// 路径注册集中在 httproutes，gateway 依赖装配和鉴权 wrapper 仍留在 transport 入口层。
func (h *Handler) Routes(jwtVerifier *auth.Verifier) http.Handler {
	// appConfigReader 的主接口只覆盖公开 App 配置；运行能力通过窄接口注入，测试或本地缺失时使用各能力通用默认值。
	runtimeCapabilities, _ := h.appConfigReader.(appconfig.RuntimeCapabilityReader)
	roomAPI := roomapi.New(roomapi.Config{
		RoomClient:          h.roomClient,
		RoomGuardClient:     h.roomGuardClient,
		RoomQueryClient:     h.roomQueryClient,
		UserProfileClient:   h.userProfileClient,
		UserCountryClient:   h.userCountryClient,
		UserRegionClient:    h.userRegionClient,
		UserSocialClient:    h.userSocialClient,
		UserHostClient:      h.userHostClient,
		AppConfigReader:     h.appConfigReader,
		WalletClient:        h.walletClient,
		GrowthLevelClient:   h.growthLevelClient,
		AchievementClient:   h.achievementClient,
		GiftCapacityEnabled: h.giftCapacityEnabled,
		GiftCapacityLimiter: h.giftCapacityLimiter,
		GiftRequestTimeout:  h.giftRequestTimeout,
		GiftMaxTargets:      h.giftMaxTargets,
		GiftMaxCount:        h.giftMaxCount,
		GiftMaxUnits:        h.giftMaxUnits,
		ObjectUploader:      h.objectUploader,
		RTCTokenConfig: tencentrtc.TokenConfig{
			Enabled:    h.tencentRTC.Enabled,
			SDKAppID:   h.tencentRTC.SDKAppID,
			SecretKey:  h.tencentRTC.SecretKey,
			TTL:        h.tencentRTC.UserSigTTL,
			RoomIDType: h.tencentRTC.RoomIDType,
			AppScene:   h.tencentRTC.AppScene,
		},
	})
	walletAPI := walletapi.New(walletapi.Config{
		WalletClient:       h.walletClient,
		RoomGuardClient:    h.roomGuardClient,
		RoomQueryClient:    h.roomQueryClient,
		UserIdentityClient: h.userIdentityClient,
		UserProfileClient:  h.userProfileClient,
		UserHostClient:     h.userHostClient,
		BroadcastClient:    h.broadcastClient,
		IMAccountImporter:  h.tencentIMImporter,
		IMPublisher:        h.tencentIMPublisher,
		IMGroupIDPrefix:    h.tencentIM.GroupIDPrefix,
		ObjectUploader:     h.objectUploader,
		WithdrawalWriter:   h.withdrawalWriter,
		WithdrawalNotifier: h.withdrawalNotifier,
	})
	userAPI := userapi.New(userapi.Config{
		UserIdentityClient: h.userIdentityClient,
		UserProfileClient:  h.userProfileClient,
		UserInviteClient:   h.userInviteClient,
		UserSocialClient:   h.userSocialClient,
		UserCPClient:       h.userCPClient,
		UserCountryClient:  h.userCountryClient,
		UserHostClient:     h.userHostClient,
		RoomQueryClient:    h.roomQueryClient,
		WalletClient:       h.walletClient,
		GrowthLevelClient:  h.growthLevelClient,
		AchievementClient:  h.achievementClient,
		BroadcastClient:    h.broadcastClient,
	})
	// WalletClient 主接口保持既有调用面；effective VIP 用窄接口做显式能力发现，
	// 便于 wallet -> gateway 滚动升级期间明确区分旧 client 和新批量契约。
	effectiveVIPClient, _ := h.walletClient.(gatewayclient.UserEffectiveVIPClient)
	messageAPI := messageapi.New(messageapi.Config{
		MessageClient:      h.messageClient,
		ActionClient:       h.messageActionClient,
		UserProfileClient:  h.userProfileClient,
		EffectiveVIPClient: effectiveVIPClient,
	})
	activityAPI := activityapi.New(activityapi.Config{
		TaskClient:           h.taskClient,
		GrowthLevelClient:    h.growthLevelClient,
		AchievementClient:    h.achievementClient,
		UserProfileClient:    h.userProfileClient,
		RoomQueryClient:      h.roomQueryClient,
		WalletClient:         h.walletClient,
		UserLeaderboard:      h.userLeaderboard,
		RuntimeCapabilities:  runtimeCapabilities,
		RegistrationReward:   h.registrationReward,
		FirstRechargeReward:  h.firstRechargeReward,
		CumulativeRecharge:   h.cumulativeRecharge,
		InviteActivityReward: h.inviteActivityReward,
		SevenDayCheckIn:      h.sevenDayCheckIn,
		LuckyGift:            h.luckyGift,
		RoomTurnoverReward:   h.roomTurnoverReward,
		WeeklyStar:           h.weeklyStar,
		CPWeeklyRank:         h.cpWeeklyRank,
		AgencyOpening:        h.agencyOpening,
		Wheel:                h.wheel,

		ActivityTemplateRuntime: h.activityTemplateRuntime,
	})
	gameAPI := gameapi.New(gameapi.Config{
		GameClient:        h.gameClient,
		UserAuthClient:    h.userClient,
		UserProfileClient: h.userProfileClient,
		WalletClient:      h.walletClient,
		StatisticsClient:  h.statisticsClient,
		JWTVerifier:       jwtVerifier,
	})
	resourceAPI := resourceapi.New(resourceapi.Config{
		WalletClient:        h.walletClient,
		RuntimeCapabilities: runtimeCapabilities,
	})
	managerAPI := managerapi.New(managerapi.Config{
		WalletClient:        h.walletClient,
		UserHostClient:      h.userHostClient,
		UserHostAdminClient: h.userHostAdminClient,
		UserProfileClient:   h.userProfileClient,
		GrowthLevelClient:   h.growthLevelClient,
		BroadcastClient:     h.broadcastClient,
	})
	userAvatarUploadClient, _ := h.userProfileClient.(gatewayclient.UserAvatarUploadClient)
	appAPI := appapi.New(appapi.Config{
		AppConfigReader:        h.appConfigReader,
		UserAuthClient:         h.userClient,
		UserProfileClient:      h.userProfileClient,
		UserAvatarUploadClient: userAvatarUploadClient,
		UserDeviceClient:       h.userDeviceClient,
		StatisticsClient:       h.statisticsClient,
		ObjectUploader:         h.objectUploader,
	})
	callbackAPI := callbackapi.New(callbackapi.Config{
		RoomClient:        h.roomClient,
		RoomGuardClient:   h.roomGuardClient,
		UserProfileClient: h.userProfileClient,
		UserHostClient:    h.userHostClient,
		TencentIM: callbackapi.TencentIMConfig{
			SDKAppID:          h.tencentIM.SDKAppID,
			AdminIdentifier:   h.tencentIM.AdminIdentifier,
			CallbackAuthToken: h.tencentIM.CallbackAuthToken,
			GroupIDPrefix:     h.tencentIM.GroupIDPrefix,
		},
		TencentRTC: callbackapi.TencentRTCConfig{
			SDKAppID:        h.tencentRTC.SDKAppID,
			CallbackSignKey: h.tencentRTC.CallbackSignKey,
			UserSigTTL:      h.tencentRTC.UserSigTTL,
		},
	})
	userHandlers := userAPI.UserHandlers()
	userHandlers.BatchUserProfiles = messageAPI.BatchUserProfiles
	userHandlers.BatchRoomDisplayProfiles = roomAPI.BatchRoomDisplayProfiles
	userHandlers.BatchUserVoiceRoomPresences = roomAPI.BatchUserVoiceRoomPresences
	userHandlers.GetMyGiftWall = walletAPI.GetMyGiftWall
	userHandlers.ListMyResources = resourceAPI.ListMyResources
	userHandlers.EquipMyResource = resourceAPI.EquipMyResource
	userHandlers.UnequipMyResource = resourceAPI.UnequipMyResource
	userSocialAction := userHandlers.UserSocialAction
	userHandlers.UserSocialAction = func(writer http.ResponseWriter, request *http.Request) {
		// /users/{user_id}/{action...} 是资料卡动作的统一入口；gift-wall 复用这个入口可避开 ServeMux 与 by-display-user-id 路由的动态段冲突。
		if request.PathValue("action") == "gift-wall" {
			if request.Method != http.MethodGet {
				httpkit.WriteError(writer, request, http.StatusMethodNotAllowed, httpkit.CodeInvalidArgument, "invalid argument")
				return
			}
			walletAPI.GetUserGiftWall(writer, request)
			return
		}
		userSocialAction(writer, request)
	}

	return httproutes.New(httproutes.Config{
		PublicWrap: func(handler http.HandlerFunc) http.Handler {
			return h.publicAPIHandler(jwtVerifier, handler)
		},
		AuthWrap: func(handler http.HandlerFunc) http.Handler {
			return h.apiHandler(jwtVerifier, handler)
		},
		ProfileWrap: func(handler http.HandlerFunc) http.Handler {
			return h.profileAPIHandler(jwtVerifier, handler)
		},
		Auth: httproutes.AuthHandlers{
			LoginPassword:             h.loginPassword,
			SetPassword:               h.setPassword,
			QuickCreateAccount:        h.quickCreateAccount,
			LoginThirdParty:           h.loginThirdParty,
			RegisterThirdParty:        h.registerThirdParty,
			CheckThirdPartyRegistered: h.checkThirdPartyRegistered,
			RefreshToken:              h.refreshToken,
			Logout:                    h.logout,
		},
		App: httproutes.AppHandlers{
			ListRegistrationCountries:     userAPI.ListRegistrationCountries,
			ListLoginRiskBlockedCountries: userAPI.ListLoginRiskBlockedCountries,
			GetAppBootstrap:               appAPI.GetAppBootstrap,
			ListH5Links:                   appAPI.ListH5Links,
			ListExploreTabs:               appAPI.ListExploreTabs,
			ListAppBanners:                appAPI.ListAppBanners,
			ListSplashScreens:             appAPI.ListSplashScreens,
			ListPopups:                    appAPI.ListPopups,
			GetAppVersion:                 appAPI.GetAppVersion,
			GetResourceGroup:              resourceAPI.GetResourceGroup,
			ListResourceShopItems:         resourceAPI.ListResourceShopItems,
			PurchaseResourceShopItem:      resourceAPI.PurchaseResourceShopItem,
			ListGifts:                     resourceAPI.ListGifts,
			ListGiftTabs:                  resourceAPI.ListGiftTabs,
			ListEmojiPacks:                resourceAPI.ListEmojiPacks,
			IssueTencentIMUserSig:         h.issueTencentIMUserSig,
			IssueTencentRTCToken:          roomAPI.IssueTencentRTCToken,
			HandleTencentIMCallback:       callbackAPI.HandleTencentIMCallback,
			HandleTencentRTCCallback:      callbackAPI.HandleTencentRTCCallback,
			UploadFile:                    appAPI.UploadFile,
			UploadAvatar:                  appAPI.UploadAvatar,
			UploadUserAvatar:              appAPI.UploadUserAvatar,
			UploadRegistrationAvatar:      appAPI.UploadRegistrationAvatar,
			ProxyEffectMedia:              appAPI.ProxyEffectMedia,
			HandlePushToken:               appAPI.HandlePushToken,
			AppHeartbeat:                  appAPI.AppHeartbeat,
			ReportAppEvents:               appAPI.ReportAppEvents,
		},
		User:        userHandlers,
		Manager:     managerAPI.ManagerHandlers(),
		Room:        roomAPI.RoomHandlers(),
		Message:     messageAPI.MessageHandlers(),
		Task:        activityAPI.TaskHandlers(),
		Level:       activityAPI.LevelHandlers(),
		Achievement: activityAPI.AchievementHandlers(),
		Wallet:      walletAPI.WalletHandlers(),
		VIP:         walletAPI.VIPHandlers(),
		Game:        gameAPI.Handlers(),
	})
}
