package com.ruoyi.novel.service.impl;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.novel.domain.AdLog;
import com.ruoyi.novel.domain.AdPlatformConfig;
import com.ruoyi.novel.service.AdSyncService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

// AdSyncServiceImpl.java
@Service
@Slf4j
public class AdSyncServiceImpl implements AdSyncService {

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public void syncToTencent(AdLog adLog, AdPlatformConfig config) {
        // 1. 构建请求参数
        String payload = buildTencentPayload(adLog, config);

        // 2. 创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(config.getAuthToken());

        // 3. 发送请求
        HttpEntity<String> entity = new HttpEntity<>(payload, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(
                config.getApiUrl(), entity, String.class);

        // 4. 处理响应
        if (response.getStatusCode() != HttpStatus.OK) {
            throw new ServiceException("腾讯广告同步失败: " + response.getBody());
        }
        log.info("腾讯广告同步成功: chapter={}, user={}", adLog.getChapterId(), adLog.getUserId());
    }

    private String buildTencentPayload(AdLog adLog, AdPlatformConfig config) {
        // 使用模板生成请求体
        return config.getParamsTemplate()
                .replace("${userId}", adLog.getUserId().toString())
                .replace("${chapterId}", adLog.getChapterId().toString())
                .replace("${timestamp}", String.valueOf(System.currentTimeMillis()));
    }

    @Override
    public void syncToPangle(AdLog adLog, AdPlatformConfig config) {
        // 1. 构建请求URL
        String url = buildPangleUrl(adLog, config);

        // 2. 创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setBearerAuth(config.getAuthToken());

        // 3. 发送请求
        HttpEntity<?> entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(
                url, HttpMethod.GET, entity, String.class);

        // 4. 处理响应
        if (response.getStatusCode() != HttpStatus.OK) {
            throw new ServiceException("穿山甲同步失败: " + response.getBody());
        }
        log.info("穿山甲同步成功: chapter={}, user={}", adLog.getChapterId(), adLog.getUserId());
    }

    private String buildPangleUrl(AdLog adLog, AdPlatformConfig config) {
        // 构建带参数的URL
        return UriComponentsBuilder.fromHttpUrl(config.getApiUrl())
                .queryParam("user", adLog.getUserId())
                .queryParam("content_id", adLog.getChapterId())
                .queryParam("event", "ad_view")
                .queryParam("ts", System.currentTimeMillis())
                .toUriString();
    }
}
