package user

import (
	"context"
	"strings"

	"hyapp/pkg/appcode"
	"hyapp/pkg/xerr"
	userdomain "hyapp/services/user-service/internal/domain/user"
)

// ResolveApp 解析或校验外部 App 身份，返回内部统一 app_code。
func (s *Service) ResolveApp(ctx context.Context, code string, packageName string, platform string) (userdomain.App, error) {
	if s.appRegistryRepository == nil {
		return userdomain.App{}, xerr.New(xerr.Unavailable, "app repository is not configured")
	}
	code = strings.TrimSpace(code)
	if code != "" {
		code = appcode.Normalize(code)
	}
	packageName = strings.TrimSpace(packageName)
	platform = strings.ToLower(strings.TrimSpace(platform))
	if packageName == "" && code == "" {
		return userdomain.App{}, xerr.New(xerr.InvalidArgument, "app_code or package_name is required")
	}

	return s.appRegistryRepository.ResolveApp(ctx, code, packageName, platform)
}

// ListApps 返回注册表中所有启用租户，供后台任务动态覆盖新 App。
func (s *Service) ListApps(ctx context.Context) ([]userdomain.App, error) {
	if s.appRegistryRepository == nil {
		return nil, xerr.New(xerr.Unavailable, "app repository is not configured")
	}
	return s.appRegistryRepository.ListApps(ctx)
}
