<?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.adx.tracking.storage.mapper.MediaCallbackMapper">

    <resultMap id="mediaCallbackResultMap" type="com.adx.tracking.storage.model.MediaCallbackRecord">
        <result property="dedupeKey" column="dedupe_key"/>
        <result property="media" column="media"/>
        <result property="qk" column="qk"/>
        <result property="callbackUrl" column="callback_url"/>
        <result property="eventType" column="event_type"/>
        <result property="eventTimeMs" column="event_time_ms"/>
        <result property="purchase" column="purchase"/>
        <result property="status" column="status"/>
        <result property="ok" column="ok_val"/>
        <result property="attempt" column="attempt"/>
        <result property="responseBody" column="response_body"/>
        <result property="errorMessage" column="error_message"/>
        <result property="createdAt" column="created_at"/>
    </resultMap>

    <insert id="insert">
        INSERT INTO media_callbacks (
            dedupe_key, media, qk, callback_url, event_type, event_time_ms, purchase,
            status, ok, attempt, response_body, error_message, created_at
        ) VALUES (
            #{dedupeKey}, #{media}, #{qk}, #{callbackUrl}, #{eventType}, #{eventTimeMs},
            #{purchase}, #{status}, #{ok}, #{attempt}, #{responseBody}, #{errorMessage},
            #{createdAt}
        )
    </insert>

    <select id="countSuccessfulByDedupeKey" resultType="int">
        SELECT COUNT(1) FROM media_callbacks WHERE dedupe_key = #{dedupeKey} AND ok = 1 LIMIT 1
    </select>

    <select id="countSuccessfulForEvent" resultType="int">
        SELECT COUNT(1)
        FROM media_callbacks
        WHERE ok = 1
          AND (
            dedupe_key = #{dedupeKey}
            OR (dedupe_key = #{legacyDedupeKey} AND event_type = #{eventType})
          )
        LIMIT 1
    </select>

    <select id="selectPendingCallbacks" resultMap="mediaCallbackResultMap">
        SELECT m.dedupe_key, m.media, m.qk, m.callback_url, m.event_type, m.event_time_ms,
               m.purchase, m.status, m.ok AS ok_val, m.attempt, m.response_body, m.error_message, m.created_at
        FROM media_callbacks m
        JOIN (
            SELECT dedupe_key, MAX(id) AS id
            FROM media_callbacks
            WHERE media = #{media} AND dedupe_key IS NOT NULL AND dedupe_key != ''
            GROUP BY dedupe_key
        ) latest ON latest.id = m.id
        WHERE m.media = #{media} AND m.ok = 0
          AND NOT EXISTS (
            SELECT 1 FROM media_callbacks ok_cb
            WHERE ok_cb.dedupe_key = m.dedupe_key AND ok_cb.ok = 1
          )
        ORDER BY m.created_at ASC
        LIMIT #{limit}
    </select>

</mapper>
