<?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.UserSignupMapper">

  <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"/>
    <result property="approved"     column="approved"/>
    <result property="displayName"  column="display_name"/>
    <result property="pwChangeYn"   column="pw_change_yn"/>
  </resultMap>

  <select id="countByUsername" resultType="int">
    SELECT COUNT(1) FROM esn_user WHERE username = #{username}
  </select>

  <select id="countByEmail" resultType="int">
    SELECT COUNT(1) FROM esn_user WHERE email = #{email}
  </select>

  <!-- 회원가입 이식: 가입자는 항상 USER·승인 대기(approved=false). -->
  <insert id="insertSignup" parameterType="com.zioinfo.esn.auth.EsnUser"
          useGeneratedKeys="true" keyProperty="id">
    INSERT INTO esn_user (username, password_hash, role, display_name, email,
                          is_active, approved, login_fail_count, locked)
    VALUES (#{username}, #{passwordHash}, 'USER', #{displayName}, #{email},
            true, false, 0, false)
  </insert>

  <select id="findByDisplayNameAndEmail" resultMap="userMap">
    SELECT id, tenant_code, username, password_hash, role, email, phone,
           is_active, last_login_at, created_at, approved, display_name, pw_change_yn
    FROM esn_user
    WHERE display_name = #{displayName} AND email = #{email}
    ORDER BY id LIMIT 1
  </select>

  <select id="findByUsernameAndEmail" resultMap="userMap">
    SELECT id, tenant_code, username, password_hash, role, email, phone,
           is_active, last_login_at, created_at, approved, display_name, pw_change_yn
    FROM esn_user
    WHERE username = #{username} AND email = #{email}
  </select>

  <!-- 비번초기화: 임시비번 적용 + 변경유도 + 잠금/실패카운트 해제(멱등). -->
  <update id="applyTempPassword">
    UPDATE esn_user
    SET password_hash = #{passwordHash}, pw_change_yn = true,
        locked = false, login_fail_count = 0
    WHERE username = #{username}
  </update>

</mapper>
