package com.red.circle.other.app.service.game;

import com.red.circle.common.business.core.enums.SysOriginPlatformEnum;
import com.red.circle.component.game.baishun.props.GameBaishunProperties;
import com.red.circle.other.infra.config.LuckyGiftApiConfig;
import com.red.circle.other.infra.config.LuckyGiftApiConfig.ApiAccount;
import com.red.circle.other.infra.database.rds.entity.game.BaishunProviderConfig;
import com.red.circle.other.infra.database.rds.service.game.BaishunProviderConfigService;
import com.red.circle.tool.core.parse.DataTypeUtils;
import com.red.circle.tool.core.text.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 百顺运行时配置解析器，优先读数据库，缺失时回退到旧配置。
 */
@Component
@RequiredArgsConstructor
public class BaishunRuntimeConfigResolver {

  private static final String DEFAULT_SYS_ORIGIN = SysOriginPlatformEnum.LIKEI.name();
  private static final String LUCKY_GIFT_START_GAME_PATH = "/lucky_gift/start_game";

  private final BaishunProviderConfigService baishunProviderConfigService;
  private final GameBaishunProperties gameBaishunProperties;
  private final LuckyGiftApiConfig luckyGiftApiConfig;

  public BaishunRuntimeConfig resolveBySysOrigin(String sysOrigin) {
    String normalizedSysOrigin = normalizeSysOrigin(sysOrigin);
    BaishunRuntimeConfig base = defaultConfig(normalizedSysOrigin);
    BaishunProviderConfig row = baishunProviderConfigService.getBySysOrigin(normalizedSysOrigin);
    if (row == null) {
      return base;
    }
    return applyRow(base, row);
  }

  public BaishunRuntimeConfig resolveByApp(String appId, String appChannel) {
    Long parsedAppId = DataTypeUtils.toLong(appId);
    BaishunRuntimeConfig base = defaultConfig(DEFAULT_SYS_ORIGIN);
    BaishunProviderConfig row = baishunProviderConfigService.getByApp(parsedAppId,
        trim(appChannel));
    if (row == null) {
      return base;
    }
    return applyRow(defaultConfig(normalizeSysOrigin(row.getSysOrigin())), row);
  }

  public LuckyGiftApiConfig.ApiAccount resolveLuckyGiftApiAccount(String sysOrigin, Long standardId) {
    ApiAccount base = luckyGiftApiConfig.getConfigByStandardId(standardId);
    BaishunRuntimeConfig config = resolveBySysOrigin(sysOrigin);

    ApiAccount resolved = new ApiAccount();
    resolved.setStandardId(base.getStandardId());
    resolved.setUrl(defaultIfBlank(
        resolveLuckyGiftApiUrl(config.getLuckyGiftUrl(), config.getPlatformBaseUrl()),
        base.getUrl()));
    resolved.setAppId(defaultIfBlank(config.getAppId(), base.getAppId()));
    resolved.setAppChannel(defaultIfBlank(config.getAppChannel(), base.getAppChannel()));
    resolved.setAppKey(defaultIfBlank(config.getAppKey(), base.getAppKey()));
    return resolved;
  }

  private BaishunRuntimeConfig defaultConfig(String sysOrigin) {
    return BaishunRuntimeConfig.builder()
        .sysOrigin(normalizeSysOrigin(sysOrigin))
        .appId(trim(gameBaishunProperties.getAppId()))
        .appKey(trim(gameBaishunProperties.getAppKey()))
        .appChannel(trim(gameBaishunProperties.getAppChannel()))
        .build();
  }

  private BaishunRuntimeConfig applyRow(BaishunRuntimeConfig base, BaishunProviderConfig row) {
    return base.toBuilder()
        .sysOrigin(normalizeSysOrigin(defaultIfBlank(row.getSysOrigin(), base.getSysOrigin())))
        .platformBaseUrl(defaultIfBlank(row.getPlatformBaseUrl(), base.getPlatformBaseUrl()))
        .luckyGiftUrl(defaultIfBlank(row.getLuckyGiftUrl(), base.getLuckyGiftUrl()))
        .appId(row.getAppId() != null && row.getAppId() > 0 ? String.valueOf(row.getAppId()) : base.getAppId())
        .appName(defaultIfBlank(row.getAppName(), base.getAppName()))
        .appChannel(defaultIfBlank(row.getAppChannel(), base.getAppChannel()))
        .appKey(defaultIfBlank(row.getAppKey(), base.getAppKey()))
        .gsp(row.getGsp() != null && row.getGsp() > 0 ? row.getGsp() : base.getGsp())
        .launchCodeTtlSeconds(row.getLaunchCodeTtlSeconds() != null && row.getLaunchCodeTtlSeconds() > 0
            ? row.getLaunchCodeTtlSeconds() : base.getLaunchCodeTtlSeconds())
        .ssTokenTtlSeconds(row.getSsTokenTtlSeconds() != null && row.getSsTokenTtlSeconds() > 0
            ? row.getSsTokenTtlSeconds() : base.getSsTokenTtlSeconds())
        .build();
  }

  private String resolveLuckyGiftApiUrl(String luckyGiftUrl, String platformBaseUrl) {
    String configuredUrl = trim(luckyGiftUrl);
    if (StringUtils.isNotBlank(configuredUrl)) {
      return trimTrailingSlash(configuredUrl);
    }
    String baseUrl = trim(platformBaseUrl);
    if (StringUtils.isBlank(baseUrl)) {
      return null;
    }
    String normalized = trimTrailingSlash(baseUrl);
    if (normalized.endsWith(LUCKY_GIFT_START_GAME_PATH)) {
      return normalized;
    }
    return normalized + LUCKY_GIFT_START_GAME_PATH;
  }

  private String trimTrailingSlash(String value) {
    String result = trim(value);
    while (StringUtils.isNotBlank(result) && result.endsWith("/")) {
      result = result.substring(0, result.length() - 1);
    }
    return result;
  }

  private String normalizeSysOrigin(String sysOrigin) {
    return StringUtils.isBlank(sysOrigin) ? DEFAULT_SYS_ORIGIN : sysOrigin.trim();
  }

  private String defaultIfBlank(String value, String fallback) {
    return StringUtils.isBlank(value) ? fallback : trim(value);
  }

  private String trim(String value) {
    return value == null ? null : value.trim();
  }
}
