<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zioinfo.esn.auth.mapper.UserAuthMapper">

  <resultMap id="userMap" type="com.zioinfo.esn.auth.EsnUser">
    <id property="id" column="id"/>
    <result property="tenantCode"   column="tenant_code"/>
    <result property="username"     column="username"/>
    <result property="passwordHash" column="password_hash"/>
    <result property="role"         column="role"/>
    <result property="email"        column="email"/>
    <result property="phone"        column="phone"/>
    <result property="active"       column="is_active"/>
    <result property="lastLoginAt"  column="last_login_at"/>
    <result property="createdAt"    column="created_at"/>
    <!-- UIWS 2FA 이식 컬럼 (91_uiws_port.sql ALTER). -->
    <result property="emailVerifyCode"   column="email_verify_code"/>
    <result property="emailVerifyExpire" column="email_verify_expire"/>
    <result property="loginFailCount"    column="login_fail_count"/>
    <result property="locked"            column="locked"/>
    <result property="otpSecret"         column="otp_secret"/>
    <result property="otpEnabled"        column="otp_enabled"/>
    <!-- UIWS 로그인 보조 이식 컬럼 (90_uiws_system.sql ALTER). -->
    <result property="approved"          column="approved"/>
    <result property="displayName"       column="display_name"/>
    <result property="pwChangeYn"        column="pw_change_yn"/>
  </resultMap>

  <select id="findByUsername" resultMap="userMap">
    SELECT id, tenant_code, username, password_hash, role, email, phone,
           is_active, last_login_at, created_at,
           email_verify_code, email_verify_expire, login_fail_count, locked, otp_secret, otp_enabled,
           approved, display_name, pw_change_yn
    FROM esn_user
    WHERE username = #{username}
  </select>

  <update id="updateLastLogin">
    UPDATE esn_user SET last_login_at = NOW() WHERE username = #{username}
  </update>

  <!-- ── UIWS 2FA 이식: 실패 카운트/잠금/인증코드 갱신 (멱등 UPDATE) ─────────────── -->

  <update id="resetLoginFail">
    UPDATE esn_user SET login_fail_count = 0 WHERE username = #{username}
  </update>

  <update id="incrementLoginFail">
    UPDATE esn_user
    SET login_fail_count = COALESCE(login_fail_count, 0) + 1,
        locked = (COALESCE(login_fail_count, 0) + 1 >= #{maxFail})
    WHERE username = #{username}
  </update>

  <update id="saveEmailCode">
    UPDATE esn_user
    SET email_verify_code = #{code}, email_verify_expire = #{expire}, login_fail_count = 0
    WHERE username = #{username}
  </update>

  <update id="clearEmailCode">
    UPDATE esn_user SET email_verify_code = NULL, email_verify_expire = NULL WHERE username = #{username}
  </update>

  <update id="unlock">
    UPDATE esn_user SET locked = false, login_fail_count = 0 WHERE username = #{username}
  </update>

  <!-- 임시/신규 비밀번호(BCrypt) 저장 + 잠금/실패카운트 해제 (평문 미저장). -->
  <update id="updatePasswordByUsername">
    UPDATE esn_user
    SET password_hash = #{passwordHash}, locked = false, login_fail_count = 0
    WHERE username = #{username}
  </update>

  <!-- ── TOTP(OTP 2차 인증) 이식 (멱등 UPDATE) ──────────────────────────────────── -->

  <!-- 보류 시크릿 저장(등록 확정 전). otp_enabled 은 verify/confirm 에서 확정. -->
  <update id="updateOtpSecret">
    UPDATE esn_user SET otp_secret = #{secret} WHERE username = #{username}
  </update>

  <!-- 등록 확정: otp_enabled=true (시크릿 유지). -->
  <update id="enableOtp">
    UPDATE esn_user SET otp_enabled = true WHERE username = #{username}
  </update>

  <!-- 마이페이지 해제: 시크릿 폐기 + otp_enabled=false. -->
  <update id="disableOtp">
    UPDATE esn_user SET otp_secret = NULL, otp_enabled = false WHERE username = #{username}
  </update>

  <!-- 관리자 OTP 초기화: 시크릿 폐기 + otp_enabled=false (다음 로그인 재등록 유도). -->
  <update id="clearOtp">
    UPDATE esn_user SET otp_secret = NULL, otp_enabled = false WHERE username = #{username}
  </update>

</mapper>
