<?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.mall.loyalty.mapper.LoyaltyMapper">

  <!-- ===== 등급 혜택 정의 ===== -->
  <select id="findTiers" resultType="com.zioinfo.mall.loyalty.MallTierBenefit">
    SELECT * FROM mall_tier_benefit
    <where><if test="activeOnly != null and activeOnly == true">active = TRUE</if></where>
    ORDER BY tier_rank ASC
  </select>
  <select id="findTierByCode" resultType="com.zioinfo.mall.loyalty.MallTierBenefit">
    SELECT * FROM mall_tier_benefit WHERE tier_code = #{tierCode}
  </select>
  <select id="findTierById" resultType="com.zioinfo.mall.loyalty.MallTierBenefit">
    SELECT * FROM mall_tier_benefit WHERE id = #{id}
  </select>
  <insert id="insertTier" parameterType="com.zioinfo.mall.loyalty.MallTierBenefit" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO mall_tier_benefit
      (tier_code, name, tier_rank, min_spend_12m, min_orders_12m, discount_rate, free_ship_threshold,
       point_earn_rate, priority_slot, birthday_coupon, exclusive_events, color, active)
    VALUES
      (#{tierCode}, #{name}, #{tierRank}, COALESCE(#{minSpend12m},0), COALESCE(#{minOrders12m},0),
       COALESCE(#{discountRate},0), #{freeShipThreshold}, COALESCE(#{pointEarnRate},1.0),
       COALESCE(#{prioritySlot},FALSE), COALESCE(#{birthdayCoupon},FALSE), COALESCE(#{exclusiveEvents},FALSE),
       #{color}, COALESCE(#{active},TRUE))
  </insert>
  <update id="updateTier">
    UPDATE mall_tier_benefit SET
      name=#{name}, tier_rank=#{tierRank},
      min_spend_12m=COALESCE(#{minSpend12m},min_spend_12m),
      min_orders_12m=COALESCE(#{minOrders12m},min_orders_12m),
      discount_rate=COALESCE(#{discountRate},discount_rate),
      free_ship_threshold=#{freeShipThreshold},
      point_earn_rate=COALESCE(#{pointEarnRate},point_earn_rate),
      priority_slot=COALESCE(#{prioritySlot},priority_slot),
      birthday_coupon=COALESCE(#{birthdayCoupon},birthday_coupon),
      exclusive_events=COALESCE(#{exclusiveEvents},exclusive_events),
      color=#{color}, active=COALESCE(#{active},active), updated_at=NOW()
    WHERE id=#{id}
  </update>
  <delete id="deleteTier">DELETE FROM mall_tier_benefit WHERE id=#{id}</delete>

  <!-- ===== 12개월 누적 구매 집계 ===== -->
  <select id="spend12m" resultType="java.util.Map">
    SELECT COALESCE(SUM(pay_amount),0) AS "spend", COUNT(*) AS "orderCount"
    FROM mall_order
    WHERE owner = #{owner}
      AND status IN ('PAID','PREPARING','SHIPPED','DELIVERED','CONFIRMED')
      AND created_at >= CURRENT_DATE - INTERVAL '365 days'
  </select>

  <!-- ===== 회원 등급 sync ===== -->
  <update id="updateMemberTier">
    UPDATE mall_member SET tier = #{tier} WHERE username = #{username}
  </update>
  <select id="allMemberUsernames" resultType="string">
    SELECT username FROM mall_member WHERE username IS NOT NULL
  </select>

  <!-- ===== 포인트 원장 ===== -->
  <insert id="insertPoint" parameterType="com.zioinfo.mall.loyalty.MallPointLedger" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO mall_point_ledger (owner, entry_type, points, order_no, reason, expire_at)
    VALUES (#{owner}, #{entryType}, #{points}, #{orderNo}, #{reason}, #{expireAt})
  </insert>
  <select id="balance" resultType="java.lang.Integer">
    SELECT COALESCE(SUM(points),0) FROM mall_point_ledger WHERE owner = #{owner}
  </select>
  <select id="history" resultType="com.zioinfo.mall.loyalty.MallPointLedger">
    SELECT * FROM mall_point_ledger WHERE owner = #{owner} ORDER BY id DESC LIMIT #{limit}
  </select>

  <!-- ===== 등급별 매출 ===== -->
  <select id="salesByTier" resultType="java.util.Map">
    SELECT COALESCE(m.tier,'BASIC') AS "tier",
           COUNT(DISTINCT o.owner) AS "customers",
           COUNT(o.id) AS "orderCount",
           COALESCE(SUM(o.pay_amount),0) AS "sales"
    FROM mall_order o
    LEFT JOIN mall_member m ON m.username = o.owner
    WHERE o.status IN ('PAID','PREPARING','SHIPPED','DELIVERED','CONFIRMED')
      AND o.created_at >= CURRENT_DATE - (#{days}::text || ' days')::interval
    GROUP BY COALESCE(m.tier,'BASIC')
    ORDER BY "sales" DESC
  </select>

</mapper>
