package tech.easyflow.ai.mapper;

import com.mybatisflex.core.BaseMapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
import tech.easyflow.ai.entity.Document;

import java.math.BigInteger;
import java.util.Date;

/**
 *  映射层。
 *
 * @author michael
 * @since 2024-08-23
 */
public interface DocumentMapper extends BaseMapper<Document> {

    /**
     * 在路径仍指向已清理 CSV 快照时原子移除数据库指针。
     *
     * @param documentId 文档 ID
     * @param manifestPath 已清理清单路径
     * @param modified 修改时间
     * @return 更新行数
     */
    @Update("UPDATE tb_document SET options=CASE "
        + "WHEN JSON_UNQUOTE(JSON_EXTRACT(options, "
        + "'$.\"parse.csvTableSnapshotPath\"'))=#{manifestPath} "
        + "AND JSON_UNQUOTE(JSON_EXTRACT(options, "
        + "'$.\"parse.metadata\".\"parse.csvTableSnapshotPath\"'))="
        + "#{manifestPath} THEN JSON_REMOVE(options, "
        + "'$.\"parse.csvTableSnapshotPath\"', "
        + "'$.\"parse.metadata\".\"parse.csvTableSnapshotPath\"') "
        + "WHEN JSON_UNQUOTE(JSON_EXTRACT(options, "
        + "'$.\"parse.csvTableSnapshotPath\"'))=#{manifestPath} "
        + "THEN JSON_REMOVE(options, "
        + "'$.\"parse.csvTableSnapshotPath\"') "
        + "ELSE JSON_REMOVE(options, "
        + "'$.\"parse.metadata\".\"parse.csvTableSnapshotPath\"') END, "
        + "modified=#{modified} "
        + "WHERE id=#{documentId} AND JSON_VALID(options)=1 AND ("
        + "JSON_UNQUOTE(JSON_EXTRACT(options, "
        + "'$.\"parse.csvTableSnapshotPath\"'))=#{manifestPath} OR "
        + "JSON_UNQUOTE(JSON_EXTRACT(options, "
        + "'$.\"parse.metadata\".\"parse.csvTableSnapshotPath\"'))="
        + "#{manifestPath})")
    int clearCsvSnapshotPath(
        @Param("documentId") BigInteger documentId,
        @Param("manifestPath") String manifestPath,
        @Param("modified") Date modified);
}
