<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zioinfo.mes.admin.mapper.AdminUserMapper">

  <resultMap id="userMap" type="com.zioinfo.mes.auth.MesUser">
    <id property="id" column="id"/>
    <result property="username" column="username"/>
    <result property="passwordHash" column="password_hash"/>
    <result property="displayName" column="display_name"/>
    <result property="role" column="role"/>
    <result property="active" column="is_active"/>
    <result property="createdAt" column="created_at"/>
  </resultMap>

  <select id="findAll" resultMap="userMap">
    SELECT id, username, password_hash, display_name, role, is_active, created_at
    FROM mes_user ORDER BY id ASC
  </select>

  <select id="findById" resultMap="userMap">
    SELECT id, username, password_hash, display_name, role, is_active, created_at
    FROM mes_user WHERE id = #{id}
  </select>

  <insert id="insert" parameterType="com.zioinfo.mes.auth.MesUser"
          useGeneratedKeys="true" keyProperty="id">
    INSERT INTO mes_user (username, password_hash, display_name, role, is_active)
    VALUES (#{username}, #{passwordHash}, #{displayName}, #{role}, #{active})
  </insert>

  <update id="updateRole">
    UPDATE mes_user SET role = #{role} WHERE id = #{id}
  </update>

  <update id="updateActive">
    UPDATE mes_user SET is_active = #{active} WHERE id = #{id}
  </update>

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

  <update id="clearOtp">
    UPDATE mes_user SET otp_secret = NULL, otp_enabled = false WHERE id = #{id}
  </update>

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

  <select id="countSuperAdmins" resultType="int">
    SELECT COUNT(*) FROM mes_user WHERE role = 'SUPERADMIN' AND is_active = TRUE
  </select>

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

</mapper>
