package com.moka.gdtauto.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.moka.gdtauto.common.Result;
import com.moka.gdtauto.entity.TencentAccount;
import com.moka.gdtauto.service.TencentAccountService;
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.entity.SysUser;
import com.moka.gdtauto.annotation.AuthUser;

import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;


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

    private final TencentAccountService tencentAccountService;

    /**
     * 同步组织账户下的广告账户信息
     * 
     * @param orgAccountId 组织账户ID（tencent_ads_auth表的accountId）
     * @return 同步结果
     */
    @Operation(
        summary = "同步组织账户下的广告账户",
        description = "根据组织账户ID，调用腾讯广告API获取该组织下所有广告账户信息并同步到数据库"
    )
    @PostMapping("/sync")
    public Result<Void> syncAccounts(
            @Parameter(description = "组织账户ID", required = true, example = "1234567890")
            @RequestParam Long orgAccountId, @AuthUser SysUser sysUser) {
        try {
            int count = tencentAccountService.syncAccountsByOrgAccountId(orgAccountId, sysUser.getJobNumber());
            return Result.<Void>success("同步成功，共同步" + count + "个广告账户")
                    .withCount(count);
        } catch (Exception e) {
            log.error("同步广告账户失败，orgAccountId={}", orgAccountId, e);
            return Result.fail("同步失败：" + e.getMessage());
        }
    }

    /**
     * 查询组织账户下的广告账户列表（分页）
     * 
     * @param orgAccountId 组织账户ID
     * @param page 页码
     * @param pageSize 每页数量
     * @return 广告账户列表
     */
    @Operation(
        summary = "查询组织账户下的广告账户列表",
        description = "根据组织账户ID分页查询该组织下所有已同步的广告账户信息"
    )
    @GetMapping("/list")
    public Result<List<TencentAccount>> listAccounts(
            @Parameter(description = "组织账户ID", required = true, example = "1234567890")
            @RequestParam Long orgAccountId,
            @Parameter(description = "页码，从1开始", example = "1")
            @RequestParam(defaultValue = "1") Long page,
            @Parameter(description = "每页数量", example = "20")
            @RequestParam(defaultValue = "20") Long pageSize, 
            @AuthUser SysUser sysUser) {
        try {
            // 计算偏移量
            long offset = (page - 1) * pageSize;
            
            // 查询总数
            LambdaQueryWrapper<TencentAccount> countWrapper = new LambdaQueryWrapper<>();
            countWrapper.eq(TencentAccount::getOrgAccountId, orgAccountId)
                       .eq(TencentAccount::getJobNumber, sysUser.getJobNumber())
                       .eq(TencentAccount::getDeleted, 0);
            long total = tencentAccountService.count(countWrapper);
            
            // 分页查询
            LambdaQueryWrapper<TencentAccount> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TencentAccount::getOrgAccountId, orgAccountId)
                   .eq(TencentAccount::getJobNumber, sysUser.getJobNumber())
                   .eq(TencentAccount::getDeleted, 0)
                   .orderByDesc(TencentAccount::getUpdateTime)
                   .last("LIMIT " + offset + ", " + pageSize);
            
            List<TencentAccount> accounts = tencentAccountService.list(wrapper);
            
            return Result.success(accounts, "查询成功")
                    .withPage(page, pageSize, total);
        } catch (Exception e) {
            log.error("查询广告账户列表失败，orgAccountId={}", orgAccountId, e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据广告账户ID查询账户详情
     * 
     * @param accountId 广告账户ID
     * @return 账户详情
     */
    @Operation(
        summary = "查询广告账户详情",
        description = "根据广告账户ID查询账户的详细信息"
    )
    @GetMapping("/detail")
    public Result<TencentAccount> getAccountDetail(
            @Parameter(description = "广告账户ID", required = true, example = "9876543210")
            @RequestParam Long id) {
        try {
            LambdaQueryWrapper<TencentAccount> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TencentAccount::getId, id)
                   .eq(TencentAccount::getDeleted, 0);
            
            TencentAccount account = tencentAccountService.getOne(wrapper);
            if (account != null) {
                return Result.success(account, "查询成功");
            } else {
                return Result.fail("未找到该广告账户信息");
            }
        } catch (Exception e) {
            log.error("查询广告账户详情失败，id={}", id, e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }

    @GetMapping("/search")
    public Result<List<TencentAccount>> searchAccount(@Parameter(description = "广告账户ID", required = false, example = "9876543210")
            @RequestParam(name = "accountId", required = false) Long accountId) {
        if (accountId == null) {
            Page<TencentAccount> page = new Page<TencentAccount>(1, 20);
            // order by id asc
            Page<TencentAccount> pageResult = tencentAccountService.page(page, new LambdaQueryWrapper<TencentAccount>().orderByAsc(TencentAccount::getId));
            return Result.success(pageResult.getRecords(), "查询成功");
        } else {
            TencentAccount account = tencentAccountService.lambdaQuery()
                    .eq(TencentAccount::getAccountId, accountId)
                    .last("LIMIT 1")
                    .oneOpt()
                    .orElse(null);
                    if (account != null) {
                        return Result.success(List.of(account), "查询成功");
                    } else {
                        return Result.fail("未找到该广告账户信息");
                    }
        }
    }
    
}
