package com.lingyue.document.repository;

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

import java.util.List;

/**
 * 文档块 Repository
 * 
 * @author lingyue
 * @since 2026-01-21
 */
@Mapper
public interface DocumentBlockRepository extends BaseMapper<DocumentBlock> {
    
    /**
     * 根据文档ID查询所有块（按顺序）
     */
    @Select("SELECT * FROM document_blocks WHERE document_id = #{documentId} ORDER BY block_index")
    List<DocumentBlock> findByDocumentId(@Param("documentId") String documentId);
    
    /**
     * 根据文档ID和块类型查询
     */
    @Select("SELECT * FROM document_blocks WHERE document_id = #{documentId} AND block_type = #{blockType} ORDER BY block_index")
    List<DocumentBlock> findByDocumentIdAndType(@Param("documentId") String documentId, 
                                                 @Param("blockType") String blockType);
    
    /**
     * 根据字符位置查找所属块
     */
    @Select("SELECT * FROM document_blocks WHERE document_id = #{documentId} " +
            "AND char_start <= #{charPos} AND char_end >= #{charPos} LIMIT 1")
    DocumentBlock findByCharPosition(@Param("documentId") String documentId, 
                                     @Param("charPos") Integer charPos);
    
    /**
     * 删除文档的所有块
     */
    @Delete("DELETE FROM document_blocks WHERE document_id = #{documentId}")
    int deleteByDocumentId(@Param("documentId") String documentId);
}
