package com.flowable.devops.repository;

import com.flowable.devops.entity.WorkflowDefinition;
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.util.List;
import java.util.Optional;

/**
 * 工作流定义数据访问接口
 */
@Repository
public interface WorkflowDefinitionRepository extends JpaRepository<WorkflowDefinition, String> {

    /**
     * 根据状态查询工作流
     */
    List<WorkflowDefinition> findByStatus(WorkflowDefinition.WorkflowStatus status);

    /**
     * 根据创建者查询工作流
     */
    List<WorkflowDefinition> findByCreatedBy(String createdBy);

    /**
     * 根据名称模糊查询
     */
    List<WorkflowDefinition> findByNameContainingIgnoreCase(String name);

    /**
     * 根据状态和创建者查询
     */
    List<WorkflowDefinition> findByStatusAndCreatedBy(
        WorkflowDefinition.WorkflowStatus status, 
        String createdBy
    );

    /**
     * 根据Flowable流程定义ID查询
     */
    Optional<WorkflowDefinition> findByFlowableProcessDefinitionId(String flowableProcessDefinitionId);

    /**
     * 查询激活状态的工作流
     */
    @Query("SELECT w FROM WorkflowDefinition w WHERE w.status = 'ACTIVE' ORDER BY w.updatedAt DESC")
    List<WorkflowDefinition> findActiveWorkflows();

    /**
     * 统计各状态的工作流数量
     */
    @Query("SELECT w.status, COUNT(w) FROM WorkflowDefinition w GROUP BY w.status")
    List<Object[]> countByStatus();

    /**
     * 根据多个条件查询（动态查询）
     */
    @Query("SELECT w FROM WorkflowDefinition w WHERE " +
           "(:status IS NULL OR w.status = :status) AND " +
           "(:createdBy IS NULL OR w.createdBy = :createdBy) AND " +
           "(:name IS NULL OR LOWER(w.name) LIKE LOWER(CONCAT('%', :name, '%'))) " +
           "ORDER BY w.updatedAt DESC")
    List<WorkflowDefinition> findByConditions(
        @Param("status") WorkflowDefinition.WorkflowStatus status,
        @Param("createdBy") String createdBy,
        @Param("name") String name
    );

    /**
     * 检查名称是否已存在
     */
    boolean existsByName(String name);

    /**
     * 检查名称是否已存在（排除指定ID）
     */
    boolean existsByNameAndIdNot(String name, String id);
}