package com.erp.dashboard.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.erp.dashboard.dto.ApiStatsDTO;
import com.erp.dashboard.entity.PullRecord;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.time.LocalDateTime;

/**
 * 拉取记录Repository
 */
@Mapper
public interface PullRecordRepository extends BaseMapper<PullRecord> {

    /**
     * 查询本月API调用统计
     */
    @Select("""
        SELECT 
            COUNT(*) as totalCalls,
            SUM(CASE WHEN pull_status = 'success' THEN 1 ELSE 0 END) as successCalls,
            SUM(CASE WHEN pull_status = 'failed' THEN 1 ELSE 0 END) as failedCalls,
            COALESCE(SUM(pulled_count), 0) as totalOrdersPulled
        FROM pull_records
        WHERE start_time BETWEEN #{monthStart} AND #{monthEnd}
          AND deleted_at IS NULL
        """)
    ApiStatsDTO selectMonthApiStats(@Param("monthStart") LocalDateTime monthStart,
                                    @Param("monthEnd") LocalDateTime monthEnd);

    /**
     * 统计今日API调用次数
     */
    @Select("""
        SELECT COUNT(*)
        FROM pull_records
        WHERE start_time BETWEEN #{todayStart} AND #{todayEnd}
          AND deleted_at IS NULL
        """)
    Long countTodayApiCalls(@Param("todayStart") LocalDateTime todayStart,
                            @Param("todayEnd") LocalDateTime todayEnd);
}
