package com.zioinfo.kintex.common.audit;

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 java.util.List;
import java.util.Map;

/** 감사 로그 매퍼(append-only). */
@Mapper
public interface AuditLogMapper {

    @Insert("""
            INSERT INTO audit_log (actor_id, actor_name, action, target_type, target_id,
                                   event_id, summary, ruleset_version, result, ip_hint)
            VALUES (#{actorId}, #{actorName}, #{action}, #{targetType}, #{targetId},
                    #{eventId}, #{summary}, #{rulesetVersion}, #{result}, #{ipHint})
            """)
    int insert(Map<String, Object> p);

    @Select("""
            <script>
            SELECT id, actor_id AS "actorId", actor_name AS "actorName", action, target_type AS "targetType",
                   target_id AS "targetId", event_id AS "eventId", summary, result,
                   to_char(created_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS"Z"') AS "createdAt"
            FROM audit_log
            <where>
              <if test="action != null and action != ''">AND action = #{action}</if>
              <if test="actorId != null and actorId != ''">AND actor_id = #{actorId}</if>
              <if test="eventId != null and eventId != ''">AND event_id = #{eventId}</if>
            </where>
            ORDER BY id DESC
            LIMIT #{size} OFFSET #{offset}
            </script>
            """)
    List<Map<String, Object>> search(@Param("action") String action, @Param("actorId") String actorId,
                                     @Param("eventId") String eventId,
                                     @Param("size") int size, @Param("offset") int offset);

    @Select("""
            <script>
            SELECT count(*) FROM audit_log
            <where>
              <if test="action != null and action != ''">AND action = #{action}</if>
              <if test="actorId != null and actorId != ''">AND actor_id = #{actorId}</if>
              <if test="eventId != null and eventId != ''">AND event_id = #{eventId}</if>
            </where>
            </script>
            """)
    long count(@Param("action") String action, @Param("actorId") String actorId,
               @Param("eventId") String eventId);
}
