<?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.erp.ai.mapper.AiKnowledgeFileMapper">

  <resultMap id="KnowledgeMap" type="com.erp.ai.model.AiKnowledgeFile">
    <id property="id" column="id"/>
    <result property="name" column="name"/>
    <result property="file_name" column="file_name"/>
    <result property="category" column="category"/>
    <result property="description" column="description"/>
    <result property="content" column="content"/>
    <result property="file_size" column="file_size"/>
    <result property="mime_type" column="mime_type"/>
    <result property="company_code" column="company_code"/>
    <result property="created_by" column="created_by"/>
    <result property="created_at" column="created_at"/>
    <result property="updated_at" column="updated_at"/>
  </resultMap>

  <select id="list" parameterType="map" resultMap="KnowledgeMap">
    SELECT id, name, file_name, category, description, content, file_size, mime_type,
           company_code, created_by, created_at, updated_at
    FROM ai_knowledge_files
    WHERE 1=1
    <if test="category != null">
      AND category = #{category}
    </if>
    <if test="company_code != null">
      AND (company_code = #{company_code} OR company_code IS NULL OR company_code = '*')
    </if>
    ORDER BY updated_at DESC
  </select>

  <select id="getById" resultMap="KnowledgeMap">
    SELECT id, name, file_name, category, description, content, file_size, mime_type,
           company_code, created_by, created_at, updated_at
    FROM ai_knowledge_files WHERE id = #{id}
  </select>

  <insert id="insert" parameterType="com.erp.ai.model.AiKnowledgeFile" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO ai_knowledge_files
      (name, file_name, category, description, content, file_size, mime_type, company_code, created_by)
    VALUES (#{name}, #{file_name}, #{category}, #{description}, #{content},
            COALESCE(#{file_size}, 0),
            #{mime_type}, #{company_code}, #{created_by})
  </insert>

  <update id="update" parameterType="com.erp.ai.model.AiKnowledgeFile">
    UPDATE ai_knowledge_files
    <set>
      <if test="name != null">name = #{name},</if>
      <if test="file_name != null">file_name = #{file_name},</if>
      <if test="category != null">category = #{category},</if>
      <if test="description != null">description = #{description},</if>
      <if test="content != null">content = #{content},</if>
      <if test="file_size != null">file_size = #{file_size},</if>
      <if test="mime_type != null">mime_type = #{mime_type},</if>
      updated_at = NOW()
    </set>
    WHERE id = #{id}
  </update>

  <delete id="delete">
    DELETE FROM ai_knowledge_files WHERE id = #{id}
  </delete>

</mapper>
