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

import com.qqchen.deploy.backend.deploy.entity.JenkinsJob;
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.util.Collection;
import java.util.Optional;
import java.util.List;

/**
 * Jenkins任务仓库接口
 */
@Repository
public interface IJenkinsJobRepository extends IBaseRepository<JenkinsJob, Long> {
    
    /**
     * 根据外部系统ID、视图ID和任务名称查询任务
     *
     * @param externalSystemId 外部系统ID
     * @param viewId 视图ID
     * @param jobName 任务名称
     * @return 任务对象
     */
    Optional<JenkinsJob> findByExternalSystemIdAndViewIdAndJobName(Long externalSystemId, Long viewId, String jobName);

    /**
     * 根据外部系统ID和视图ID查询所有任务
     *
     * @param externalSystemId 外部系统ID
     * @param viewId 视图ID
     * @return 任务列表
     */
    List<JenkinsJob> findByExternalSystemIdAndViewId(Long externalSystemId, Long viewId);

    /**
     * 统计视图下的任务数量
     *
     * @param viewId 视图ID
     * @return 任务数量
     */
    Long countByViewIdAndDeletedFalse(Long viewId);
    
    /**
     * 批量查询视图的任务数量（用于解决N+1查询问题）
     * @param viewIds 视图ID集合
     * @return Object数组列表，[0]=viewId, [1]=count
     */
    @Query("SELECT j.viewId as viewId, COUNT(j.id) as count " +
           "FROM JenkinsJob j " +
           "WHERE j.viewId IN :viewIds AND j.deleted = false " +
           "GROUP BY j.viewId")
    List<Object[]> countByViewIds(@Param("viewIds") Collection<Long> viewIds);
} 