<?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.BackupMapper">

  <resultMap id="backupMap" type="com.zioinfo.signage.domain.BackupVo">
    <id     property="id" column="id"/>
    <result property="tenantCode" column="tenant_code"/>
    <result property="storeCode" column="store_code"/>
    <result property="backupType" column="backup_type"/>
    <result property="fileName" column="file_name"/>
    <result property="fileSize" column="file_size"/>
    <result property="md5" column="md5"/>
    <result property="filePath" column="file_path"/>
    <result property="status" column="status"/>
    <result property="backupAt" column="backup_at"/>
    <result property="restoredAt" column="restored_at"/>
    <result property="createdAt" column="created_at"/>
  </resultMap>

  <select id="findAll" resultMap="backupMap">
    SELECT id, tenant_code, store_code, backup_type, file_name, file_size, md5, file_path, status, backup_at, restored_at, created_at
    FROM signage_backup
    <where>
      <if test="tenantCode != null and tenantCode != ''">AND tenant_code = #{tenantCode}</if>
      <if test="status != null and status != ''">AND status = #{status}</if>
      <if test="keyword != null and keyword != ''">AND file_name ILIKE '%' || #{keyword} || '%'</if>
    </where>
    ORDER BY created_at DESC
  </select>

  <select id="findById" resultMap="backupMap">
    SELECT id, tenant_code, store_code, backup_type, file_name, file_size, md5, file_path, status, backup_at, restored_at, created_at FROM signage_backup WHERE id = #{id}
  </select>

  <insert id="insert" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO signage_backup (tenant_code, store_code, backup_type, file_name, file_size, md5, file_path, status)
    VALUES (#{tenantCode}, #{storeCode}, #{backupType}, #{fileName}, #{fileSize}, #{md5}, #{filePath}, #{status})
  </insert>

  <update id="update">
    UPDATE signage_backup SET
      tenant_code = #{tenantCode},
      store_code = #{storeCode},
      backup_type = #{backupType},
      file_name = #{fileName},
      file_size = #{fileSize},
      md5 = #{md5},
      file_path = #{filePath},
      status = #{status}
    WHERE id = #{id}
  </update>

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

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

</mapper>
