<?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.cms.banner.mapper.BannerMapper">

  <resultMap id="bannerMap" type="com.zioinfo.cms.banner.CmsBanner">
    <id property="id" column="id"/>
    <result property="name" column="name"/>
    <result property="bannerType" column="banner_type"/>
    <result property="imageUrl" column="image_url"/>
    <result property="linkUrl" column="link_url"/>
    <result property="position" column="position"/>
    <result property="targetRule" column="target_rule"/>
    <result property="sortOrder" column="sort_order"/>
    <result property="active" column="is_active"/>
    <result property="startAt" column="start_at"/>
    <result property="endAt" column="end_at"/>
    <result property="createdBy" column="created_by"/>
    <result property="createdAt" column="created_at"/>
  </resultMap>

  <select id="findAll" resultMap="bannerMap">
    SELECT * FROM cms_banner
    <where>
      <if test="bannerType != null and bannerType != ''">AND banner_type = #{bannerType}</if>
      <if test="position != null and position != ''">AND position = #{position}</if>
    </where>
    ORDER BY sort_order ASC NULLS LAST, id DESC
  </select>

  <select id="findActiveNow" resultMap="bannerMap">
    SELECT * FROM cms_banner
    WHERE is_active = TRUE
      AND (start_at IS NULL OR start_at &lt;= NOW())
      AND (end_at IS NULL OR end_at &gt;= NOW())
    <if test="position != null and position != ''">AND position = #{position}</if>
    ORDER BY sort_order ASC NULLS LAST, id DESC
  </select>

  <select id="findById" resultMap="bannerMap">SELECT * FROM cms_banner WHERE id = #{id}</select>

  <insert id="insert" parameterType="com.zioinfo.cms.banner.CmsBanner" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO cms_banner (name, banner_type, image_url, link_url, position, target_rule, sort_order, is_active, start_at, end_at, created_by)
    VALUES (#{name}, #{bannerType}, #{imageUrl}, #{linkUrl}, #{position}, #{targetRule}::jsonb, #{sortOrder}, #{active}, #{startAt}, #{endAt}, #{createdBy})
  </insert>

  <update id="update" parameterType="com.zioinfo.cms.banner.CmsBanner">
    UPDATE cms_banner SET name = #{name}, banner_type = #{bannerType}, image_url = #{imageUrl}, link_url = #{linkUrl},
      position = #{position}, target_rule = #{targetRule}::jsonb, sort_order = #{sortOrder}, is_active = #{active},
      start_at = #{startAt}, end_at = #{endAt}
    WHERE id = #{id}
  </update>

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

</mapper>
