package com.pandoli365.bibimbap.mapper;

import com.pandoli365.bibimbap.data.UnityFeedItemData;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

@Mapper
public interface UnityFeedItemsMapper {

    @Insert("""
            INSERT INTO unity_feed_items (
                source_id,
                guid,
                title,
                link_url,
                published_at
            ) VALUES (
                #{sourceId},
                #{guid},
                #{title},
                #{linkUrl},
                #{publishedAt}
            )
            ON CONFLICT (source_id, guid) DO NOTHING
            """)
    int insertIgnoreDup(UnityFeedItemData item);

    @Select("""
            SELECT
                i.id,
                i.source_id AS sourceId,
                i.guid,
                i.title,
                i.link_url AS linkUrl,
                i.published_at AS publishedAt,
                i.is_acknowledged AS isAcknowledged,
                i.detected_at AS detectedAt,
                s.name AS sourceName
            FROM unity_feed_items i
            JOIN unity_feed_sources s ON s.id = i.source_id
            WHERE i.is_acknowledged = false
            ORDER BY i.detected_at DESC
            LIMIT #{limit}
            """)
    List<UnityFeedItemData> listUnacknowledged(@Param("limit") int limit);

    @Select("""
            SELECT count(*)
            FROM unity_feed_items
            WHERE is_acknowledged = false
            """)
    int countUnacknowledged();

    @Update("""
            UPDATE unity_feed_items
            SET is_acknowledged = true
            WHERE id = #{itemId}
            """)
    int acknowledge(@Param("itemId") long itemId);

    @Select("""
            SELECT EXISTS(
                SELECT 1
                FROM unity_feed_items
                WHERE source_id = #{sourceId}
                  AND guid = #{guid}
            )
            """)
    boolean existsByGuid(@Param("sourceId") long sourceId, @Param("guid") String guid);
}
