package com.zioinfo.kintex.system.errorlog;

import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.Map;

/** 오류 로그 매퍼(error_log). 요약 1줄만 저장(스택트레이스 금지). 테넌트 스코프. */
@Mapper
public interface ErrorLogMapper {

    @Insert("INSERT INTO error_log (tenant_id, error_code, summary, path, method, actor_id) "
            + "VALUES (#{tenantId}, #{errorCode}, #{summary}, #{path}, #{method}, #{actorId})")
    int insert(Map<String, Object> p);

    @Select("""
            <script>
            SELECT id, error_code AS "errorCode", summary, path, method, actor_id AS "actorId",
                   to_char(created_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS"Z"') AS "createdAt"
            FROM error_log
            <where>
              AND tenant_id = #{tenantId}
              <if test="errorCode != null and errorCode != ''">AND error_code = #{errorCode}</if>
            </where>
            ORDER BY id DESC
            LIMIT #{size} OFFSET #{offset}
            </script>
            """)
    List<Map<String, Object>> search(@Param("tenantId") String tenantId, @Param("errorCode") String errorCode,
                                     @Param("size") int size, @Param("offset") int offset);

    @Select("""
            <script>
            SELECT count(*) FROM error_log
            <where>
              AND tenant_id = #{tenantId}
              <if test="errorCode != null and errorCode != ''">AND error_code = #{errorCode}</if>
            </where>
            </script>
            """)
    long count(@Param("tenantId") String tenantId, @Param("errorCode") String errorCode);
}
