package com.ruoyi.novel.service.impl;

import com.ruoyi.novel.domain.AdPlatformConfig;
import com.ruoyi.novel.mapper.AdPlatformConfigMapper;
import com.ruoyi.novel.service.AdConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

// AdConfigServiceImpl.java
@Service
public class AdConfigServiceImpl implements AdConfigService {

    @Autowired
    private AdPlatformConfigMapper configMapper;

    private Map<String, AdPlatformConfig> adConfigCache;
    private final Object lock = new Object();

    @PostConstruct
    public void init() {
        refreshConfigCache();
    }

    @Override
    public void refreshConfigCache() {
        synchronized (lock) {
            adConfigCache = configMapper.selectList(null).stream()
                    .collect(Collectors.toMap(AdPlatformConfig::getPlatformCode, Function.identity()));

            // 如果数据库为空，初始化默认配置
            if (adConfigCache.isEmpty()) {
                initDefaultConfigs();
            }
        }
    }

    private void initDefaultConfigs() {
        adConfigCache = new HashMap<>();
        adConfigCache.put("tencent", new AdPlatformConfig(
                "tencent", "腾讯广告",
                "https://ad.tencent.com/track",
                "default_tencent_token",
                "{\"user_id\":\"${userId}\",\"content_id\":\"${chapterId}\"}"
        ));
        adConfigCache.put("pangle", new AdPlatformConfig(
                "pangle", "穿山甲",
                "https://ad.pangle.com/api/v1/event",
                "default_pangle_token",
                "{\"user\":\"${userId}\",\"content_id\":\"${chapterId}\"}"
        ));

        // 保存默认配置到数据库
        adConfigCache.values().forEach(configMapper::insert);
    }

    @Override
    public AdPlatformConfig getConfig(String platformCode) {
        if (adConfigCache == null) {
            refreshConfigCache();
        }
        return adConfigCache.get(platformCode);
    }
}