<?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.datamate.collection.infrastructure.persistence.mapper.CollectionTaskMapper">

  <!-- Result Map -->
  <resultMap id="CollectionTaskResultMap" type="com.datamate.collection.domain.model.entity.CollectionTask">
    <id property="id" column="id"/>
    <result property="name" column="name"/>
    <result property="description" column="description"/>
    <result property="config" column="config"/>
    <result property="status" column="status" typeHandler="org.apache.ibatis.type.EnumTypeHandler"/>
    <result property="syncMode" column="sync_mode"/>
    <result property="scheduleExpression" column="schedule_expression"/>
    <result property="retryCount" column="retry_count"/>
    <result property="timeoutSeconds" column="timeout_seconds"/>
    <result property="maxRecords" column="max_records"/>
    <result property="sortField" column="sort_field"/>
    <result property="lastExecutionId" column="last_execution_id"/>
    <result property="createdAt" column="created_at"/>
    <result property="updatedAt" column="updated_at"/>
    <result property="createdBy" column="created_by"/>
    <result property="updatedBy" column="updated_by"/>
  </resultMap>

  <!-- Base Column List (tasks) -->
  <sql id="Base_Column_List">
    id,
    name, description, config, status, sync_mode,
    schedule_expression, retry_count, timeout_seconds, max_records, sort_field,
    last_execution_id, created_at, updated_at, created_by, updated_by
  </sql>

  <!-- Update Status -->
  <update id="updateStatus">
    UPDATE t_dc_collection_tasks SET status = #{status}, updated_at = NOW() WHERE id = #{id}
  </update>

  <!-- Update Last Execution -->
  <update id="updateLastExecution">
    UPDATE t_dc_collection_tasks SET last_execution_id = #{lastExecutionId}, updated_at = NOW() WHERE id = #{id}
  </update>

  <!-- Select Active Tasks for Scheduling -->
  <select id="selectActiveTasks" resultMap="CollectionTaskResultMap">
    SELECT <include refid="Base_Column_List"/> FROM t_dc_collection_tasks
    WHERE status IN ('READY', 'RUNNING')
      AND schedule_expression IS NOT NULL
    ORDER BY created_at DESC
  </select>
</mapper>
