package com.moka.gdtauto.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.moka.gdtauto.common.Result;
import com.moka.gdtauto.entity.SysUser;
import com.moka.gdtauto.entity.TencentConversion;
import com.moka.gdtauto.service.TencentConversionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import com.moka.gdtauto.annotation.AuthUser;

import java.util.List;

/**
 * 腾讯广告转化归因控制器
 * 
 * @author moka
 * @since 2026-02-06
 */
@Tag(name = "转化归因管理", description = "腾讯广告转化归因信息同步与查询")
@Slf4j
@RestController
@RequestMapping("/api/gdt/conversion")
@RequiredArgsConstructor
public class TencentConversionController {

    private final TencentConversionService tencentConversionService;

    /**
     * 同步转化归因数据
     * 
     * @param orgAccountId 组织账户ID
     * @param accountId 广告账户ID
     * @return 同步结果
     */
    @Operation(
        summary = "同步转化归因数据",
        description = "根据组织账户ID和广告账户ID，调用腾讯广告API获取该账户下符合条件的转化归因并同步到数据库（短剧用户增长注册变现）"
    )
    @PostMapping("/sync")
    public Result<Void> syncConversions(
            @Parameter(description = "广告账户ID", required = true, example = "69781948")
            @RequestParam Long accountId, 
            @Parameter(description = "组织账户ID", required = true, example = "123456789")
            @RequestParam Long orgAccountId,
            @AuthUser SysUser user) {
        try {
            int count = tencentConversionService.syncConversions(user.getJobNumber(), orgAccountId, accountId);
            return Result.<Void>success("同步成功，共同步" + count + "条转化归因")
                    .withCount(count);
        } catch (Exception e) {
            log.error("同步转化归因失败，orgAccountId={}, accountId={}", orgAccountId, accountId, e);
            return Result.fail("同步失败：" + e.getMessage());
        }
    }

    /**
     * 查询转化归因列表（分页）
     * 
     * @param page 页码
     * @param pageSize 每页数量
     * @return 转化归因列表
     */
    @Operation(
        summary = "查询转化归因列表",
        description = "分页查询已同步的转化归因信息"
    )
    @GetMapping("/list")
    public Result<List<TencentConversion>> listConversions(
            @Parameter(description = "页码，从1开始", example = "1")
            @RequestParam(defaultValue = "1") Long page,
            @Parameter(description = "每页数量", example = "20")
            @RequestParam(defaultValue = "20") Long pageSize) {
        try {
            // 计算偏移量
            long offset = (page - 1) * pageSize;
            
            // 查询总数
            long total = tencentConversionService.count();
            
            // 分页查询
            LambdaQueryWrapper<TencentConversion> wrapper = new LambdaQueryWrapper<>();
            wrapper.orderByDesc(TencentConversion::getUpdateTime)
                   .last("LIMIT " + offset + ", " + pageSize);
            
            List<TencentConversion> conversions = tencentConversionService.list(wrapper);
            
            return Result.success(conversions, "查询成功")
                    .withPage(page, pageSize, total);
        } catch (Exception e) {
            log.error("查询转化归因列表失败", e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据转化ID查询转化详情
     * 
     * @param conversionId 转化ID
     * @return 转化详情
     */
    @Operation(
        summary = "查询转化详情",
        description = "根据转化ID查询转化的详细信息"
    )
    @GetMapping("/detail")
    public Result<TencentConversion> getConversionDetail(
            @Parameter(description = "转化ID", required = true, example = "72627668")
            @RequestParam Long conversionId) {
        try {
            LambdaQueryWrapper<TencentConversion> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TencentConversion::getConversionId, conversionId);
            
            TencentConversion conversion = tencentConversionService.getOne(wrapper);
            if (conversion != null) {
                return Result.success(conversion, "查询成功");
            } else {
                return Result.fail("未找到该转化归因信息");
            }
        } catch (Exception e) {
            log.error("查询转化详情失败，conversionId={}", conversionId, e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }

    @Operation(
        summary = "查询所有转化归因",
        description = "查询所有已同步的转化归因信息"
    )
    @GetMapping("/all")
    public Result<List<TencentConversion>> getAllConversions() {
        try {
            List<TencentConversion> conversions = tencentConversionService.list();
            return Result.success(conversions, "查询成功");
        } catch (Exception e) {
            log.error("查询所有转化归因失败", e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }
}
