<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.moyz.adi.common.mapper.KnowledgeBaseMapper">
    <select id="searchByAdmin" resultType="com.moyz.adi.common.entity.KnowledgeBase">
        select *
        from adi_knowledge_base
        where is_deleted = false
        <if test="keyword != null and keyword != ''">
            and title like CONCAT('%', #{keyword}, '%')
        </if>
        order by update_time desc
    </select>

    <select id="searchByUser" resultType="com.moyz.adi.common.entity.KnowledgeBase">
        select *
        from adi_knowledge_base
        where is_deleted = false
        <choose>
            <when test="includeOthersPublic">
                and (is_public = true or owner_id = #{ownerId})
            </when>
            <otherwise>
                and owner_id = #{ownerId}
            </otherwise>
        </choose>
        <if test="keyword != null and keyword != ''">
            and title like CONCAT('%', #{keyword}, '%')
        </if>
        order by star_count desc,update_time desc
    </select>

    <select id="countCreatedByTimePeriod" resultType="Integer">
        select count(1)
        from adi_knowledge_base
        where is_deleted = false
          and create_time between #{beginTime} and #{endTime}
    </select>

    <select id="countAllCreated" resultType="Integer">
        select count(1)
        from adi_knowledge_base
        where is_deleted = false
    </select>

    <update id="updateStatByUuid">
        update adi_knowledge_base
        set item_count      = (select count(1)
                               from adi_knowledge_base_item
                               where kb_uuid = #{uuid}
                                 and is_deleted = false),
            embedding_count = #{embeddingCount}
        where uuid = #{uuid}
    </update>

    <select id="getByItemUuid" resultType="com.moyz.adi.common.entity.KnowledgeBase">
        select a.*
        from adi_knowledge_base a
                 inner join adi_knowledge_base_item b on a.id = b.kb_id
        where a.is_deleted = false
          and b.uuid = #{itemUuid}
    </select>
</mapper>
