<?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="mailSentHistory">

  <!-- ────────────────────────────────────────────────────────
       검색 조건 Fragment
       Node.js: searchTerm(제목/받는사람), status, accountId, startDate, endDate
       deleted 필터: onlyDeleted / includeDeleted
  ──────────────────────────────────────────────────────── -->
  <sql id="mailSentHistorySearchCondition">
    <!-- 삭제 상태 필터 -->
    <choose>
      <when test="only_deleted != null and only_deleted == true">
        AND DELETED_DATE IS NOT NULL
      </when>
      <when test="include_deleted == null or include_deleted == false">
        AND DELETED_DATE IS NULL
      </when>
      <!-- includeDeleted == true → 필터 없음 -->
    </choose>

    <!-- 발송 상태 필터 (success / failed / draft) -->
    <if test='status != null and status != "" and status != "all"'>
      AND STATUS = #{status}
    </if>

    <!-- 계정 필터 -->
    <if test="account_id != null and account_id != ''">
      AND ACCOUNT_ID = #{account_id}
    </if>

    <!-- 날짜 범위 -->
    <if test="start_date != null and start_date != ''">
      AND SENT_AT &gt;= #{start_date}::TIMESTAMP
    </if>
    <if test="end_date != null and end_date != ''">
      AND SENT_AT &lt;= #{end_date}::TIMESTAMP
    </if>

    <!-- 검색어 (제목, 받는사람, 참조) -->
    <if test="search_term != null and search_term != ''">
      AND (SUBJECT ILIKE '%' || #{search_term} || '%'
           OR TO_EMAILS  ILIKE '%' || #{search_term} || '%'
           OR CC_EMAILS  ILIKE '%' || #{search_term} || '%')
    </if>
  </sql>

  <!-- ────────────────────────────────────────────────────────
       목록 조회
  ──────────────────────────────────────────────────────── -->
  <select id="getMailSentHistoryList" parameterType="map" resultType="map">
    SELECT
        ID
        , COMPANY_CODE
        , ACCOUNT_ID
        , ACCOUNT_NAME
        , ACCOUNT_EMAIL
        , TO_EMAILS
        , CC_EMAILS
        , BCC_EMAILS
        , SUBJECT
        , TEMPLATE_ID
        , TEMPLATE_NAME
        , STATUS
        , MESSAGE_ID
        , ERROR_MESSAGE
        , ACCEPTED
        , REJECTED
        , IS_DRAFT
        , SENT_AT
        , DELETED_DATE
        , CREATED_DATE
        , UPDATED_DATE
    FROM MAIL_SENT_HISTORY
    WHERE 1=1
    <include refid="common.companyCodeFilter"/>
    <include refid="mailSentHistorySearchCondition"/>
    <include refid="common.dynamicOrderBy"/>
    <include refid="common.pagination"/>
  </select>

  <select id="getMailSentHistoryListCnt" parameterType="map" resultType="int">
    SELECT COUNT(*)
    FROM MAIL_SENT_HISTORY
    WHERE 1=1
    <include refid="common.companyCodeFilter"/>
    <include refid="mailSentHistorySearchCondition"/>
  </select>

  <!-- ────────────────────────────────────────────────────────
       단건 조회
  ──────────────────────────────────────────────────────── -->
  <select id="getMailSentHistoryInfo" parameterType="map" resultType="map">
    SELECT
        ID
        , COMPANY_CODE
        , ACCOUNT_ID
        , ACCOUNT_NAME
        , ACCOUNT_EMAIL
        , TO_EMAILS
        , CC_EMAILS
        , BCC_EMAILS
        , SUBJECT
        , HTML_CONTENT
        , TEMPLATE_ID
        , TEMPLATE_NAME
        , ATTACHMENTS
        , STATUS
        , MESSAGE_ID
        , ERROR_MESSAGE
        , ACCEPTED
        , REJECTED
        , IS_DRAFT
        , SENT_AT
        , DELETED_DATE
        , CREATED_DATE
        , UPDATED_DATE
    FROM MAIL_SENT_HISTORY
    WHERE ID = #{id}
    <include refid="common.companyCodeFilter"/>
  </select>

  <!-- ────────────────────────────────────────────────────────
       등록 (UUID id 직접 제공, Node.js의 saveSentMail / saveDraft)
  ──────────────────────────────────────────────────────── -->
  <insert id="insertMailSentHistory" parameterType="map">
    INSERT INTO MAIL_SENT_HISTORY (
        ID
        , COMPANY_CODE
        , ACCOUNT_ID
        , ACCOUNT_NAME
        , ACCOUNT_EMAIL
        , TO_EMAILS
        , CC_EMAILS
        , BCC_EMAILS
        , SUBJECT
        , HTML_CONTENT
        , TEMPLATE_ID
        , TEMPLATE_NAME
        , ATTACHMENTS
        , STATUS
        , MESSAGE_ID
        , ERROR_MESSAGE
        , ACCEPTED
        , REJECTED
        , IS_DRAFT
        , SENT_AT
        , CREATED_DATE
        , UPDATED_DATE
    ) VALUES (
        #{id}
        , #{company_code}
        , #{account_id}
        , #{account_name}
        , #{account_email}
        , #{to_emails}
        , #{cc_emails}
        , #{bcc_emails}
        , #{subject}
        , #{html_content}
        , #{template_id}
        , #{template_name}
        , #{attachments}
        , #{status}
        , #{message_id}
        , #{error_message}
        , #{accepted}
        , #{rejected}
        , #{is_draft}
        , #{sent_at}
        , NOW()
        , NOW()
    )
  </insert>

  <!-- ────────────────────────────────────────────────────────
       수정 (동적 SET — draft 업데이트에 활용)
  ──────────────────────────────────────────────────────── -->
  <update id="updateMailSentHistory" parameterType="map">
    UPDATE MAIL_SENT_HISTORY
    <set>
      <if test="subject != null">SUBJECT = #{subject},</if>
      <if test="html_content != null">HTML_CONTENT = #{html_content},</if>
      <if test="to_emails != null">TO_EMAILS = #{to_emails},</if>
      <if test="cc_emails != null">CC_EMAILS = #{cc_emails},</if>
      <if test="bcc_emails != null">BCC_EMAILS = #{bcc_emails},</if>
      <if test="attachments != null">ATTACHMENTS = #{attachments},</if>
      <if test="status != null">STATUS = #{status},</if>
      <if test="is_draft != null">IS_DRAFT = #{is_draft},</if>
      <if test="account_id != null">ACCOUNT_ID = #{account_id},</if>
      <if test="account_name != null">ACCOUNT_NAME = #{account_name},</if>
      <if test="account_email != null">ACCOUNT_EMAIL = #{account_email},</if>
      <if test="template_id != null">TEMPLATE_ID = #{template_id},</if>
      <if test="template_name != null">TEMPLATE_NAME = #{template_name},</if>
      <if test="error_message != null">ERROR_MESSAGE = #{error_message},</if>
      UPDATED_DATE = NOW()
    </set>
    WHERE ID = #{id}
    <include refid="common.companyCodeFilter"/>
  </update>

  <!-- ────────────────────────────────────────────────────────
       소프트 삭제 (DELETED_DATE 세팅)
  ──────────────────────────────────────────────────────── -->
  <update id="softDeleteMailSentHistory" parameterType="map">
    UPDATE MAIL_SENT_HISTORY
    SET
        DELETED_DATE = NOW()
        , UPDATED_DATE = NOW()
    WHERE ID = #{id}
      AND DELETED_DATE IS NULL
    <include refid="common.companyCodeFilter"/>
  </update>

  <!-- ────────────────────────────────────────────────────────
       복구 (DELETED_DATE 초기화)
  ──────────────────────────────────────────────────────── -->
  <update id="restoreMailSentHistory" parameterType="map">
    UPDATE MAIL_SENT_HISTORY
    SET
        DELETED_DATE = NULL
        , UPDATED_DATE = NOW()
    WHERE ID = #{id}
      AND DELETED_DATE IS NOT NULL
    <include refid="common.companyCodeFilter"/>
  </update>

  <!-- ────────────────────────────────────────────────────────
       영구 삭제 (물리 삭제)
  ──────────────────────────────────────────────────────── -->
  <delete id="permanentDeleteMailSentHistory" parameterType="map">
    DELETE FROM MAIL_SENT_HISTORY
    WHERE ID = #{id}
    <include refid="common.companyCodeFilter"/>
  </delete>

  <!-- ────────────────────────────────────────────────────────
       일괄 소프트 삭제
  ──────────────────────────────────────────────────────── -->
  <update id="bulkSoftDeleteMailSentHistory" parameterType="map">
    UPDATE MAIL_SENT_HISTORY
    SET DELETED_DATE = NOW(), UPDATED_DATE = NOW()
    WHERE ID IN
    <foreach collection="ids" item="id" open="(" separator="," close=")">
      #{id}
    </foreach>
      AND DELETED_DATE IS NULL
    <include refid="common.companyCodeFilter"/>
  </update>

  <!-- ────────────────────────────────────────────────────────
       일괄 복구
  ──────────────────────────────────────────────────────── -->
  <update id="bulkRestoreMailSentHistory" parameterType="map">
    UPDATE MAIL_SENT_HISTORY
    SET DELETED_DATE = NULL, UPDATED_DATE = NOW()
    WHERE ID IN
    <foreach collection="ids" item="id" open="(" separator="," close=")">
      #{id}
    </foreach>
      AND DELETED_DATE IS NOT NULL
    <include refid="common.companyCodeFilter"/>
  </update>

  <!-- ────────────────────────────────────────────────────────
       일괄 영구 삭제
  ──────────────────────────────────────────────────────── -->
  <delete id="bulkPermanentDeleteMailSentHistory" parameterType="map">
    DELETE FROM MAIL_SENT_HISTORY
    WHERE ID IN
    <foreach collection="ids" item="id" open="(" separator="," close=")">
      #{id}
    </foreach>
    <include refid="common.companyCodeFilter"/>
  </delete>

  <!-- ────────────────────────────────────────────────────────
       통계 조회 (Node.js: totalSent, successCount, failedCount,
                           todayCount, thisMonthCount)
  ──────────────────────────────────────────────────────── -->
  <select id="getMailSentHistoryStatistics" parameterType="map" resultType="map">
    SELECT
      COUNT(*)                                                              AS TOTAL_SENT,
      COUNT(CASE WHEN STATUS = 'success' THEN 1 END)                       AS SUCCESS_COUNT,
      COUNT(CASE WHEN STATUS = 'failed'  THEN 1 END)                       AS FAILED_COUNT,
      COUNT(CASE WHEN SENT_AT &gt;= CURRENT_DATE THEN 1 END)               AS TODAY_COUNT,
      COUNT(CASE WHEN SENT_AT &gt;= DATE_TRUNC('month', NOW()) THEN 1 END) AS THIS_MONTH_COUNT
    FROM MAIL_SENT_HISTORY
    WHERE DELETED_DATE IS NULL
    <include refid="common.companyCodeFilter"/>
    <if test="account_id != null and account_id != ''">
      AND ACCOUNT_ID = #{account_id}
    </if>
  </select>

</mapper>
