package com.lingyue.extract.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lingyue.extract.entity.SourceDocument;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 来源文档 Repository
 * 
 * @author lingyue
 * @since 2026-01-22
 */
@Mapper
public interface SourceDocumentRepository extends BaseMapper<SourceDocument> {
    
    /**
     * 根据项目ID查询来源文档列表
     */
    @Select("SELECT * FROM extract_source_documents WHERE project_id = #{projectId} ORDER BY display_order")
    List<SourceDocument> findByProjectId(@Param("projectId") String projectId);
    
    /**
     * 根据关联的 Document ID 查询
     */
    @Select("SELECT * FROM extract_source_documents WHERE document_id = #{documentId}")
    List<SourceDocument> findByDocumentId(@Param("documentId") String documentId);
    
    /**
     * 根据项目ID和别名查询
     */
    @Select("SELECT * FROM extract_source_documents WHERE project_id = #{projectId} AND alias = #{alias}")
    SourceDocument findByProjectIdAndAlias(@Param("projectId") String projectId, @Param("alias") String alias);
    
    /**
     * 删除项目的所有来源文档
     */
    @Delete("DELETE FROM extract_source_documents WHERE project_id = #{projectId}")
    int deleteByProjectId(@Param("projectId") String projectId);
    
    /**
     * 统计项目来源文档数量
     */
    @Select("SELECT COUNT(*) FROM extract_source_documents WHERE project_id = #{projectId}")
    int countByProjectId(@Param("projectId") String projectId);
    
    /**
     * 获取项目最大显示顺序
     */
    @Select("SELECT COALESCE(MAX(display_order), 0) FROM extract_source_documents WHERE project_id = #{projectId}")
    int getMaxDisplayOrder(@Param("projectId") String projectId);
}
