package com.moka.gdtauto.service;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.moka.gdtauto.GdtAutoApplication;
import com.moka.gdtauto.client.TencentAdsApiClientFactory;
import com.moka.gdtauto.common.Constant;
import com.moka.gdtauto.task.SyncAdgroupSystemStatusTask;
import com.tencent.ads.model.v3.AdgroupsGetResponseData;
import com.tencent.ads.model.v3.FilteringStruct;
import com.tencent.ads.model.v3.FilterOperator;
import com.tencent.ads.v3.TencentAds;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;

import java.util.ArrayList;
import java.util.List;

/**
 * 获取广告状态测试
 * https://developers.e.qq.com/v3.0/docs/api/adgroups/get
 *  mvn test -Dtest=GetAdGroupStatusTest#testGetAdGroupStatusWithCursorPagination -Dspring.profiles.active=test
 *  mvn test -Dtest=GetAdGroupStatusTest#testSyncAdgroupSystemStatus -Dspring.profiles.active=test
 * @author moka
 * @since 2026-03-05
 */
@SpringBootTest(classes = GdtAutoApplication.class)
@ActiveProfiles("test")
class GetAdGroupStatusTest {

    @Autowired
    private TencentAdsApiClientFactory clientFactory;
    @Autowired
    private SyncAdgroupSystemStatusTask syncAdgroupSystemStatusTask;


    @Test
    @DisplayName("同步广告状态")
    void testSyncAdgroupSystemStatus() {
        syncAdgroupSystemStatusTask.syncAdgroupSystemStatus();
    }

    private static final Long ORG_ACCOUNT_ID = 41644744L;
    private static final Long TEST_ACCOUNT_ID = 75323409L;
    private static final String TEST_JOB_NUMBER = "12458";

    /**
     * 100 adgroup IDs to query
     */
    private static final List<Long> ADGROUP_IDS = List.of(
        86787637171L,86790720528L
    );

    @Test
    @DisplayName("使用游标分页获取广告状态")
    void testGetAdGroupStatusWithCursorPagination() {
        System.out.println("\n========================================");
        System.out.println("开始获取广告状态");
        System.out.println("账户ID: " + TEST_ACCOUNT_ID);
        System.out.println("广告ID数量: " + ADGROUP_IDS.size());
        System.out.println("========================================\n");

        try {
            TencentAds tencentAds = clientFactory.getTencentAds(TEST_JOB_NUMBER, ORG_ACCOUNT_ID);
            tencentAds.setDebug(true);

            // Build filtering: adgroup_id IN [100 adgroup IDs]
            List<FilteringStruct> filtering = new ArrayList<>();
            FilteringStruct filter = new FilteringStruct();
            filter.setField("adgroup_id");
            filter.setOperator(FilterOperator.IN);
            List<String> values = new ArrayList<>();
            for (Long id : ADGROUP_IDS) {
                values.add(String.valueOf(id));
            }
            filter.setValues(values);
            filtering.add(filter);

            // Fields to retrieve
            List<String> fields = List.of(
                "adgroup_id",
                "system_status"
            );

            // Cursor pagination: query all 100 IDs in a single request (API max is 100 per IN filter)
            String paginationMode = "PAGINATION_MODE_CURSOR";
            Long pageSize = 100L;

            Gson gson = new GsonBuilder().setPrettyPrinting().create();

            System.out.println("========== 请求参数（cursor模式，首次请求无cursor）==========");

            AdgroupsGetResponseData response = tencentAds.adgroups()
                .adgroupsGet(
                    TEST_ACCOUNT_ID,
                    filtering,
                    null,       // page (not used in cursor mode)
                    pageSize,
                    false,      // is_deleted
                    fields,
                    paginationMode,
                    null        // cursor: null for first request
                );

            System.out.println("========== 响应结果 ==========");
            System.out.println(gson.toJson(response));
            System.out.println("========================================\n");

            if (response == null || response.getList() == null || response.getList().isEmpty()) {
                System.out.println("⚠️  返回结果为空");
            } else {
                int totalFetched = response.getList().size();
                System.out.println("本次返回: " + totalFetched + " 条");

                // Print adgroup_id + configured_status summary
                response.getList().forEach(item ->
                    System.out.println("  广告ID: " + item.getAdgroupId()
                        + "  名称: " + item.getAdgroupName()
                        + "  状态: " + item.getSystemStatus()
                        + "  状态: " + Constant.getAdGroupStatusValue(item.getSystemStatus().getValue()))
                );

                if (response.getPageInfo() != null) {
                    System.out.println("📊 总数: " + response.getPageInfo().getTotalNumber());
                    System.out.println("📊 总页数: " + response.getPageInfo().getTotalPage());
                }
            }

            System.out.println("\n✅ 查询完成");

        } catch (Exception e) {
            System.err.println("\n❌ API调用失败");
            System.err.println("错误信息: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("测试失败", e);
        }
    }
}
