<?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.mapper.UserMapper">

  <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="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"/>
    <!-- password_hash 는 resultMap에서 제외 — API 응답 미노출 -->
  </resultMap>

  <select id="findAll" resultMap="userMap">
    SELECT id, tenant_code, username, role, email, phone, is_active, last_login_at, created_at
    FROM esn_user
    <where>
      <if test="tenantCode != null and tenantCode != ''">AND tenant_code = #{tenantCode}</if>
      <if test="role != null and role != ''">AND role = #{role}</if>
    </where>
    ORDER BY username
  </select>

  <select id="findById" resultMap="userMap">
    SELECT id, tenant_code, username, role, email, phone, is_active, last_login_at, created_at
    FROM esn_user WHERE id = #{id}
  </select>

  <select id="findByUsername" resultType="com.zioinfo.esn.auth.EsnUser">
    SELECT id, tenant_code, username, password_hash, role, email, phone,
           is_active, last_login_at, created_at
    FROM esn_user WHERE username = #{username}
  </select>

  <insert id="insert" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO esn_user (tenant_code, username, password_hash, role, email, phone, is_active)
    VALUES (#{tenantCode}, #{username}, #{passwordHash}, #{role}, #{email}, #{phone}, #{active})
  </insert>

  <update id="update">
    UPDATE esn_user SET
      tenant_code = #{tenantCode},
      role        = #{role},
      email       = #{email},
      phone       = #{phone},
      is_active   = #{active}
    WHERE id = #{id}
  </update>

  <update id="updatePassword">
    UPDATE esn_user SET password_hash = #{passwordHash} WHERE id = #{id}
  </update>

  <delete id="delete">DELETE FROM esn_user WHERE id = #{id}</delete>

</mapper>
