<?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.analytics.mapper.AnalyticsMapper">
  <select id="todayTotals" resultType="java.util.Map">
    SELECT COALESCE(SUM(pay_amount),0) AS "totalSales", COUNT(*) AS "orderCount"
    FROM mall_order
    WHERE created_at::date = CURRENT_DATE AND status NOT IN ('CANCELLED','PENDING')
  </select>
  <select id="salesByStore" resultType="java.util.Map">
    SELECT s.id AS "storeId", s.code AS "storeCode", s.name AS "storeName",
           COALESCE(SUM(o.pay_amount),0) AS "sales", COUNT(o.id) AS "orderCount"
    FROM mall_store s
    LEFT JOIN mall_order o ON o.store_id = s.id
      AND o.created_at >= CURRENT_DATE - (#{days}::text || ' days')::interval
      AND o.status NOT IN ('CANCELLED','PENDING')
    GROUP BY s.id, s.code, s.name
    ORDER BY "sales" DESC
  </select>
  <select id="topProducts" resultType="java.util.Map">
    SELECT id AS "productId", name, sales_count AS "salesCount", rating_avg AS "ratingAvg"
    FROM mall_product ORDER BY sales_count DESC LIMIT #{limit}
  </select>
  <select id="bigOrders" resultType="java.util.Map">
    SELECT order_no AS "orderNo", store_id AS "storeId", pay_amount AS "payAmount",
           receiver_name AS "receiverName", status, created_at AS "createdAt"
    FROM mall_order
    WHERE pay_amount >= #{minAmount} AND status NOT IN ('CANCELLED')
    ORDER BY pay_amount DESC LIMIT #{limit}
  </select>
  <select id="dailyTrend" resultType="java.util.Map">
    SELECT created_at::date AS "date", COALESCE(SUM(pay_amount),0) AS "sales", COUNT(*) AS "orderCount"
    FROM mall_order
    WHERE created_at >= CURRENT_DATE - (#{days}::text || ' days')::interval
      AND status NOT IN ('CANCELLED','PENDING')
    GROUP BY created_at::date ORDER BY "date"
  </select>
</mapper>
