package com.emotion.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.emotion.dto.response.AiConfigCallStatsItem;
import com.emotion.entity.AiConfig;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * AI配置Mapper接口
 * 
 * @author system
 * @date 2025-10-30
 */
@Mapper
public interface AiConfigMapper extends BaseMapper<AiConfig> {

    /**
     * 按 AI 配置统计 Coze 接口调用次数（通过 workflow_id 关联）
     *
     * @param limit 返回条数限制
     * @return 统计列表（按调用次数倒序）
     */
    @Select({
            "SELECT",
            "  c.id               AS configId,",
            "  c.config_name      AS configName,",
            "  c.config_key       AS configKey,",
            "  c.provider         AS provider,",
            "  c.config_type      AS configType,",
            "  c.workflow_id      AS workflowId,",
            "  c.is_enabled       AS isEnabled,",
            "  c.is_default       AS isDefault,",
            "  COALESCE(COUNT(a.id), 0) AS callCount",
            "FROM t_ai_config c",
            "LEFT JOIN t_coze_api_call a",
            "  ON a.workflow_id = c.workflow_id",
            " AND a.is_deleted = 0",
            "WHERE c.is_deleted = 0",
            "GROUP BY",
            "  c.id, c.config_name, c.config_key, c.provider, c.config_type,",
            "  c.workflow_id, c.is_enabled, c.is_default",
            "ORDER BY callCount DESC",
            "LIMIT #{limit}"
    })
    List<AiConfigCallStatsItem> selectAiConfigCallStats(@Param("limit") Integer limit);
}