package com.ruoyi.novel.service.impl;

import com.ruoyi.novel.service.IAdService;

@Service
public class AdServiceImpl implements IAdService {

    @Autowired
    private AdLogMapper adLogMapper;

    @Autowired
    private AdPlatformClient adPlatformClient;

    private Map<String, AdPlatformConfig> adConfigCache;
    private final Object lock = new Object();
    @Override
    @Transactional
    public void logAdView(AdLog adLog) {
        // 防止重复记录
        int count = adLogMapper.countByUserAndChapter(adLog.getUserId(), adLog.getChapterId());
        if (count > 0) {
            log.warn("Duplicate ad log: user={}, chapter={}", adLog.getUserId(), adLog.getChapterId());
            return;
        }

        adLog.setSyncStatus(0); // 未同步状态
        adLogMapper.insert(adLog);
    }

    @Override
    @Async("adTaskExecutor")
    public void syncWithAdPlatform(AdLog adLog) {
        try {
            adPlatformClient.syncAdPlatform(adLog);
            adLog.setSyncStatus(1); // 同步成功
        } catch (Exception e) {
            log.error("Ad sync failed: {}", e.getMessage());
            adLog.setSyncStatus(2); // 同步失败
        }
        adLogMapper.updateById(adLog);
    }

    @Override
    @Scheduled(fixedRate = 300000) // 每5分钟执行一次
    public void retryFailedSyncs() {
        List<AdLog> failedLogs = adLogMapper.selectUnsyncedLogs();
        failedLogs.forEach(log -> {
            log.info("Retrying ad sync for log: {}", log.getId());
            this.syncWithAdPlatform(log);
        });
    }

    @Override
    public Map<String, AdPlatformConfig> loadAdConfigs() {
        if (adConfigCache == null) {
            synchronized (lock) {
                if (adConfigCache == null) {
                    // 实际应从数据库加载
                    adConfigCache = new HashMap<>();
                    adConfigCache.put("tencent", new AdPlatformConfig(
                            "tencent", "腾讯广告",
                            "https://ad.tencent.com/track",
                            "token_123",
                            "{\"user_id\":\"${userId}\",\"chapter_id\":\"${chapterId}\"}"
                    ));
                    // 其他平台配置...
                }
            }
        }
        return adConfigCache;
    }
//    @Override
//    @Transactional
//    public void logAdView(AdLog adLog) {
//        adLogMapper.insertAdLog(adLog);
//    }

    @Override
    public void syncWithAdPlatform(AdLog adLog) {
        // 根据平台选择不同实现
        switch (adLog.getAdPlatform()) {
            case "tencent":
                adPlatformClient.syncTencent(adLog);
                break;
            case "pangle":
                adPlatformClient.syncPangle(adLog);
                break;
            default:
                log.warn("Unknown ad platform: {}", adLog.getAdPlatform());
        }
    }
}
