package com.datamate.datamanagement.infrastructure.persistence.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.datamate.datamanagement.domain.model.knowledge.KnowledgeItem;
import com.datamate.datamanagement.interfaces.dto.KnowledgeItemSearchResponse;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface KnowledgeItemMapper extends BaseMapper<KnowledgeItem> {
    @Select("""
        SELECT
            ki.id AS id,
            ki.set_id AS setId,
            ks.name AS setName,
            ki.content_type AS contentType,
            ki.source_type AS sourceType,
            ki.source_dataset_id AS sourceDatasetId,
            ki.source_file_id AS sourceFileId,
            CASE
                WHEN ki.source_type = 'DATASET_FILE' THEN df.file_name
                ELSE ki.source_file_id
            END AS fileName,
            df.file_size AS fileSize,
            CASE
                WHEN ki.source_type = 'FILE_UPLOAD' THEN ki.content
                ELSE NULL
            END AS content,
            ki.relative_path AS relativePath,
            ki.created_at AS createdAt,
            ki.updated_at AS updatedAt
        FROM t_dm_knowledge_items ki
        LEFT JOIN t_dm_knowledge_sets ks ON ki.set_id = ks.id
        LEFT JOIN t_dm_dataset_files df ON ki.source_file_id = df.id AND ki.source_type = 'DATASET_FILE'
        WHERE (ki.source_type = 'FILE_UPLOAD' AND (ki.source_file_id LIKE CONCAT('%', #{keyword}, '%')
           OR ki.relative_path LIKE CONCAT('%', #{keyword}, '%')))
           OR (ki.source_type = 'DATASET_FILE' AND (df.file_name LIKE CONCAT('%', #{keyword}, '%')
           OR ki.relative_path LIKE CONCAT('%', #{keyword}, '%')))
        ORDER BY ki.created_at DESC
        """)
    IPage<KnowledgeItemSearchResponse> searchFileItems(IPage<?> page, @Param("keyword") String keyword);

    @Select("""
        SELECT COALESCE(SUM(df.file_size), 0)
        FROM t_dm_knowledge_items ki
        LEFT JOIN t_dm_dataset_files df ON ki.source_file_id = df.id
        WHERE ki.source_type = 'DATASET_FILE'
        """)
    Long sumDatasetFileSize();
}
