package auth

import (
	"context"
	"sort"
	"strings"

	"hyapp/pkg/appcode"
	authdomain "hyapp/services/user-service/internal/domain/auth"
)

// ListLoginRiskBlockedCountries 返回当前 App 实际生效的登录地区风控词表。
// 静态配置和后台动态配置都下发给 App；App 可异步做本地风险提示，最终封禁仍以服务端 worker 为准。
func (s *Service) ListLoginRiskBlockedCountries(ctx context.Context) ([]authdomain.LoginRiskCountryBlock, error) {
	if !s.loginRiskPolicy.Enabled {
		return nil, nil
	}
	appCode := appcode.FromContext(ctx)
	blocks := make([]authdomain.LoginRiskCountryBlock, 0, len(s.loginRiskPolicy.UnsupportedCountries))
	seen := map[string]struct{}{}
	for _, country := range s.loginRiskPolicy.UnsupportedCountries {
		countryCode := normalizeCountryCode(country)
		if countryCode == "" {
			continue
		}
		block := authdomain.LoginRiskCountryBlock{
			AppCode:     appCode,
			Keyword:     countryCode,
			CountryCode: countryCode,
			Enabled:     true,
		}
		blocks = appendUniqueCountryBlock(blocks, seen, block)
	}
	if s.authRepository != nil {
		dynamicBlocks, err := s.authRepository.ListEnabledLoginRiskCountryBlocks(ctx)
		if err != nil {
			return nil, err
		}
		for _, block := range dynamicBlocks {
			block.AppCode = appcode.Normalize(block.AppCode)
			block.Keyword = strings.TrimSpace(block.Keyword)
			block.CountryCode = normalizeCountryCode(block.CountryCode)
			block.Enabled = true
			if block.Keyword == "" {
				continue
			}
			blocks = appendUniqueCountryBlock(blocks, seen, block)
		}
	}
	sort.SliceStable(blocks, func(i, j int) bool {
		if blocks[i].CountryCode != blocks[j].CountryCode {
			return blocks[i].CountryCode < blocks[j].CountryCode
		}
		return strings.ToLower(blocks[i].Keyword) < strings.ToLower(blocks[j].Keyword)
	})
	return blocks, nil
}

func appendUniqueCountryBlock(blocks []authdomain.LoginRiskCountryBlock, seen map[string]struct{}, block authdomain.LoginRiskCountryBlock) []authdomain.LoginRiskCountryBlock {
	key := strings.ToLower(block.CountryCode + "\x00" + block.Keyword)
	if _, ok := seen[key]; ok {
		return blocks
	}
	seen[key] = struct{}{}
	return append(blocks, block)
}

func (s *Service) countryBlockedByStaticPolicy(countryCode string) bool {
	for _, country := range s.loginRiskPolicy.UnsupportedCountries {
		if normalizeCountryCode(country) == countryCode {
			return true
		}
	}
	return false
}

func (s *Service) countryBlockedByDynamicPolicy(ctx context.Context, countryCode string) (bool, error) {
	if s.authRepository == nil {
		return false, nil
	}
	blocks, err := s.authRepository.ListEnabledLoginRiskCountryBlocks(ctx)
	if err != nil {
		return false, err
	}
	for _, block := range blocks {
		if normalizeCountryCode(block.CountryCode) == countryCode || normalizeCountryCode(block.Keyword) == countryCode {
			return true, nil
		}
	}
	return false, nil
}
