package com.pandoli365.bibimbap.mapper;

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;

@Mapper
public interface UserBadgesMapper {

    @Insert("""
            INSERT INTO user_badges (user_id, badge_key, awarded_by)
            VALUES (#{userId}, #{badgeKey}, NULL)
            ON CONFLICT (user_id, badge_key) WHERE revoked_at IS NULL DO NOTHING
            """)
    int insertIgnore(@Param("userId") long userId, @Param("badgeKey") String badgeKey);

    @Insert("""
            INSERT INTO user_badges (user_id, badge_key, awarded_by)
            VALUES (#{userId}, #{badgeKey}, #{awardedBy})
            """)
    int insert(@Param("userId") long userId,
               @Param("badgeKey") String badgeKey,
               @Param("awardedBy") long awardedBy);

    @Select("""
            SELECT EXISTS(
                SELECT 1 FROM user_badges
                WHERE user_id = #{userId}
                  AND badge_key = #{badgeKey}
                  AND revoked_at IS NULL
            )
            """)
    boolean existsActive(@Param("userId") long userId, @Param("badgeKey") String badgeKey);

    @Update("""
            UPDATE user_badges
            SET revoked_at = now(),
                revoke_reason = #{reason}
            WHERE user_id = #{userId}
              AND badge_key = #{badgeKey}
              AND revoked_at IS NULL
            """)
    int revoke(@Param("userId") long userId,
               @Param("badgeKey") String badgeKey,
               @Param("reason") String reason);
}
