<?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.ga.core.mapper.settle.BatchJobLogMapper">

    <resultMap id="LogMap" type="com.ga.core.vo.settle.BatchJobLogVO"/>

    <insert id="insert" parameterType="com.ga.core.vo.settle.BatchJobLogVO" useGeneratedKeys="true" keyProperty="jobId">
        INSERT INTO batch_job_log (job_name, job_params, settle_month, status,
                                   started_at, triggered_by)
        VALUES (#{jobName}, #{jobParams}, #{settleMonth}, COALESCE(#{status},'STARTED'),
                NOW(), #{triggeredBy})
    </insert>

    <update id="update" parameterType="com.ga.core.vo.settle.BatchJobLogVO">
        UPDATE batch_job_log SET
            status = #{status},
            current_step = #{currentStep},
            progress_pct = #{progressPct},
            total_count = #{totalCount},
            processed_count = #{processedCount},
            error_count = #{errorCount},
            error_message = #{errorMessage},
            finished_at = CASE WHEN #{status} IN ('COMPLETED','FAILED') THEN NOW() ELSE finished_at END,
            duration_sec = CASE
                WHEN #{status} IN ('COMPLETED','FAILED')
                THEN EXTRACT(EPOCH FROM (NOW() - started_at))::int
                ELSE duration_sec END
        WHERE job_id = #{jobId}
    </update>

    <select id="selectById" resultMap="LogMap">
        SELECT * FROM batch_job_log WHERE job_id = #{jobId}
    </select>

    <select id="selectLatest" resultMap="LogMap">
        SELECT * FROM batch_job_log WHERE job_name = #{jobName}
        ORDER BY started_at DESC LIMIT 1
    </select>

    <select id="selectList" resultMap="LogMap">
        SELECT * FROM batch_job_log
        <where>
            <if test="jobName != null and jobName != ''">AND job_name = #{jobName}</if>
            <if test="settleMonth != null and settleMonth != ''">AND settle_month = #{settleMonth}</if>
        </where>
        ORDER BY started_at DESC
    </select>

    <select id="isRunning" resultType="int">
        SELECT COUNT(*) FROM batch_job_log
        WHERE job_name = #{jobName} AND status IN ('STARTED','RUNNING')
    </select>

</mapper>
