package com.flowable.devops.repository;

import com.flowable.devops.entity.WorkflowExecution;
import org.springframework.data.jpa.repository.JpaRepository;
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.List;
import java.util.Optional;

/**
 * 工作流执行记录数据访问接口
 */
@Repository
public interface WorkflowExecutionRepository extends JpaRepository<WorkflowExecution, String> {

    /**
     * 根据工作流定义ID查询执行记录
     */
    List<WorkflowExecution> findByWorkflowDefinitionIdOrderByStartedAtDesc(String workflowDefinitionId);

    /**
     * 根据执行状态查询
     */
    List<WorkflowExecution> findByStatus(WorkflowExecution.ExecutionStatus status);

    /**
     * 根据触发者查询
     */
    List<WorkflowExecution> findByTriggeredByOrderByStartedAtDesc(String triggeredBy);

    /**
     * 根据Flowable流程实例ID查询
     */
    Optional<WorkflowExecution> findByFlowableProcessInstanceId(String flowableProcessInstanceId);

    /**
     * 根据触发方式查询
     */
    List<WorkflowExecution> findByTriggerType(WorkflowExecution.TriggerType triggerType);

    /**
     * 查询指定时间范围内的执行记录
     */
    @Query("SELECT e FROM WorkflowExecution e WHERE e.startedAt BETWEEN :startTime AND :endTime ORDER BY e.startedAt DESC")
    List<WorkflowExecution> findByStartedAtBetween(
        @Param("startTime") LocalDateTime startTime,
        @Param("endTime") LocalDateTime endTime
    );

    /**
     * 查询正在运行的执行记录
     */
    @Query("SELECT e FROM WorkflowExecution e WHERE e.status = 'RUNNING' ORDER BY e.startedAt")
    List<WorkflowExecution> findRunningExecutions();

    /**
     * 统计各状态的执行数量
     */
    @Query("SELECT e.status, COUNT(e) FROM WorkflowExecution e GROUP BY e.status")
    List<Object[]> countByStatus();

    /**
     * 统计指定工作流的执行次数
     */
    @Query("SELECT COUNT(e) FROM WorkflowExecution e WHERE e.workflowDefinitionId = :workflowId")
    long countByWorkflowDefinitionId(@Param("workflowId") String workflowId);

    /**
     * 查询最近的执行记录
     */
    @Query("SELECT e FROM WorkflowExecution e ORDER BY e.startedAt DESC")
    List<WorkflowExecution> findRecentExecutions();

    /**
     * 根据多个条件查询（动态查询）
     */
    @Query("SELECT e FROM WorkflowExecution e WHERE " +
           "(:workflowDefinitionId IS NULL OR e.workflowDefinitionId = :workflowDefinitionId) AND " +
           "(:status IS NULL OR e.status = :status) AND " +
           "(:triggeredBy IS NULL OR e.triggeredBy = :triggeredBy) AND " +
           "(:triggerType IS NULL OR e.triggerType = :triggerType) " +
           "ORDER BY e.startedAt DESC")
    List<WorkflowExecution> findByConditions(
        @Param("workflowDefinitionId") String workflowDefinitionId,
        @Param("status") WorkflowExecution.ExecutionStatus status,
        @Param("triggeredBy") String triggeredBy,
        @Param("triggerType") WorkflowExecution.TriggerType triggerType
    );

    /**
     * 查询失败的执行记录
     */
    @Query("SELECT e FROM WorkflowExecution e WHERE e.status = 'FAILED' ORDER BY e.startedAt DESC")
    List<WorkflowExecution> findFailedExecutions();

    /**
     * 删除指定时间之前的执行记录（清理历史数据）
     */
    @Query("DELETE FROM WorkflowExecution e WHERE e.endedAt < :cutoffTime AND e.status IN ('COMPLETED', 'FAILED', 'CANCELLED')")
    void deleteCompletedExecutionsBefore(@Param("cutoffTime") LocalDateTime cutoffTime);
}