<?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.signage.admin.mapper.AuditLogMapper">

  <resultMap id="auditMap" type="com.zioinfo.signage.admin.dto.AuditLog">
    <id     property="id"         column="id"/>
    <result property="tenantCode" column="tenant_code"/>
    <result property="username"   column="username"/>
    <result property="action"     column="action"/>
    <result property="resource"   column="resource"/>
    <result property="resourceId" column="resource_id"/>
    <result property="detail"     column="detail"/>
    <result property="ipAddress"  column="ip_address"/>
    <result property="userAgent"  column="user_agent"/>
    <result property="success"    column="success"/>
    <result property="createdAt"  column="created_at"/>
  </resultMap>

  <insert id="insert" parameterType="com.zioinfo.signage.admin.dto.AuditLog"
          useGeneratedKeys="true" keyProperty="id">
    INSERT INTO signage_audit_log
      (tenant_code, username, action, resource, resource_id, detail, ip_address, user_agent, success)
    VALUES
      (#{tenantCode}, #{username}, #{action}, #{resource}, #{resourceId}, #{detail},
       #{ipAddress}, #{userAgent}, #{success})
  </insert>

  <sql id="filters">
    <where>
      <if test="tenantCode != null and tenantCode != ''">AND tenant_code = #{tenantCode}</if>
      <if test="username != null and username != ''">AND username = #{username}</if>
      <if test="action != null and action != ''">AND action = #{action}</if>
      <if test="resource != null and resource != ''">AND resource = #{resource}</if>
      <if test="from != null">AND created_at &gt;= #{from}</if>
      <if test="to != null">AND created_at &lt;= #{to}</if>
    </where>
  </sql>

  <select id="find" resultMap="auditMap">
    SELECT id, tenant_code, username, action, resource, resource_id, detail,
           ip_address, user_agent, success, created_at
    FROM signage_audit_log
    <include refid="filters"/>
    ORDER BY id DESC
    LIMIT #{limit}
  </select>

  <select id="count" resultType="long">
    SELECT COUNT(*)
    FROM signage_audit_log
    <include refid="filters"/>
  </select>

</mapper>
