package com.qqchen.deploy.backend.deploy.repository;

import com.qqchen.deploy.backend.deploy.entity.JenkinsBuild;
import com.qqchen.deploy.backend.framework.repository.IBaseRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Optional;
import java.util.List;

/**
 * Jenkins构建信息仓库接口
 */
@Repository
public interface IJenkinsBuildRepository extends IBaseRepository<JenkinsBuild, Long> {
    
    /**
     * 根据外部系统ID、任务ID和构建号查询构建信息
     *
     * @param externalSystemId 外部系统ID
     * @param jobId 任务ID
     * @param buildNumber 构建号
     * @return 构建信息
     */
    Optional<JenkinsBuild> findByExternalSystemIdAndJobIdAndBuildNumber(
        Long externalSystemId, Long jobId, Integer buildNumber);

    /**
     * 根据外部系统ID和任务ID查询所有构建信息
     *
     * @param externalSystemId 外部系统ID
     * @param jobId 任务ID
     * @return 构建信息列表
     */
    List<JenkinsBuild> findByExternalSystemIdAndJobId(Long externalSystemId, Long jobId);

    /**
     * 查询指定任务的最新构建记录
     *
     * @param externalSystemId 外部系统ID
     * @param jobId 任务ID
     * @return 最新的构建记录
     */
    Optional<JenkinsBuild> findTopByExternalSystemIdAndJobIdOrderByBuildNumberDesc(
        Long externalSystemId, Long jobId);

    /**
     * 统计任务下的构建数量
     *
     * @param jobId 任务ID
     * @return 构建数量
     */
    Long countByJobIdAndDeletedFalse(Long jobId);
    
    /**
     * 批量查询任务的构建数量（用于解决N+1查询问题）
     * @param jobIds 任务ID集合
     * @return Object数组列表，[0]=jobId, [1]=count
     */
    @Query("SELECT b.jobId as jobId, COUNT(b.id) as count " +
           "FROM JenkinsBuild b " +
           "WHERE b.jobId IN :jobIds AND b.deleted = false " +
           "GROUP BY b.jobId")
    List<Object[]> countByJobIds(@Param("jobIds") Collection<Long> jobIds);
    
    /**
     * 查询指定时间之后开始的构建记录（用于构建通知）
     *
     * @param externalSystemId 外部系统ID
     * @param starttime 构建开始时间
     * @return 构建记录列表
     */
    List<JenkinsBuild> findByExternalSystemIdAndStarttimeAfter(
        Long externalSystemId, LocalDateTime starttime);
    
    /**
     * 批量查询多个任务的最新构建记录（用于解决N+1查询问题）
     * 
     * @param externalSystemId 外部系统ID
     * @param jobIds 任务ID集合
     * @return 最新构建记录列表
     */
    @Query("""
        SELECT b FROM JenkinsBuild b
        WHERE b.externalSystemId = :externalSystemId
        AND b.jobId IN :jobIds
        AND (b.jobId, b.buildNumber) IN (
            SELECT b2.jobId, MAX(b2.buildNumber)
            FROM JenkinsBuild b2
            WHERE b2.externalSystemId = :externalSystemId
            AND b2.jobId IN :jobIds
            GROUP BY b2.jobId
        )
        """)
    List<JenkinsBuild> findLatestBuildsByJobIds(
        @Param("externalSystemId") Long externalSystemId,
        @Param("jobIds") Collection<Long> jobIds);
}