package com.zioinfo.kintex.system.loginhistory;

import org.apache.ibatis.annotations.*;

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

/** 로그인 이력 매퍼(login_history). 저장 값은 마스킹만(원문 금지). 테넌트 스코프. */
@Mapper
public interface LoginHistoryMapper {

    @Insert("INSERT INTO login_history (tenant_id, user_id, email_masked, result, fail_reason, ip_masked, user_agent) "
            + "VALUES (#{tenantId}, #{userId}, #{emailMasked}, #{result}, #{failReason}, #{ipMasked}, #{userAgent})")
    int insert(Map<String, Object> p);

    @Select("""
            <script>
            SELECT id, user_id AS "userId", email_masked AS "emailMasked", result,
                   fail_reason AS "failReason", ip_masked AS "ipMasked", user_agent AS "userAgent",
                   to_char(created_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS"Z"') AS "createdAt"
            FROM login_history
            <where>
              AND tenant_id = #{tenantId}
              <if test="result != null and result != ''">AND result = #{result}</if>
              <if test="userId != null and userId != ''">AND user_id = #{userId}</if>
            </where>
            ORDER BY id DESC
            LIMIT #{size} OFFSET #{offset}
            </script>
            """)
    List<Map<String, Object>> search(@Param("tenantId") String tenantId, @Param("result") String result,
                                     @Param("userId") String userId,
                                     @Param("size") int size, @Param("offset") int offset);

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