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

  <resultMap id="regionMap" type="com.zioinfo.signage.domain.RegionVo">
    <id     property="id" column="id"/>
    <result property="tenantCode" column="tenant_code"/>
    <result property="regionCode" column="region_code"/>
    <result property="regionName" column="region_name"/>
    <result property="dcName" column="dc_name"/>
    <result property="description" column="description"/>
    <result property="active" column="is_active"/>
    <result property="createdAt" column="created_at"/>
  </resultMap>

  <select id="findAll" resultMap="regionMap">
    SELECT id, tenant_code, region_code, region_name, dc_name, description, is_active, created_at
    FROM signage_region
    <where>
      <if test="tenantCode != null and tenantCode != ''">AND tenant_code = #{tenantCode}</if>
      <if test="keyword != null and keyword != ''">AND region_name ILIKE '%' || #{keyword} || '%'</if>
    </where>
    ORDER BY created_at DESC
  </select>

  <select id="findById" resultMap="regionMap">
    SELECT id, tenant_code, region_code, region_name, dc_name, description, is_active, created_at FROM signage_region WHERE id = #{id}
  </select>

  <insert id="insert" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO signage_region (tenant_code, region_code, region_name, dc_name, description, is_active)
    VALUES (#{tenantCode}, #{regionCode}, #{regionName}, #{dcName}, #{description}, #{active})
  </insert>

  <update id="update">
    UPDATE signage_region SET
      tenant_code = #{tenantCode},
      region_code = #{regionCode},
      region_name = #{regionName},
      dc_name = #{dcName},
      description = #{description},
      is_active = #{active}
    WHERE id = #{id}
  </update>

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

  <select id="countAll" resultType="long">
    SELECT COUNT(*) FROM signage_region
    <where>
      <if test="tenantCode != null and tenantCode != ''">AND tenant_code = #{tenantCode}</if>
    </where>
  </select>

</mapper>
