-- name: ListRecentOrderSummaries :many
SELECT
    o.id,
    o.order_number,
    o.status,
    o.total_amount_cents,
    o.currency,
    o.shipping_method,
    o.shipping_price_cents,
    o.created_at,
    COALESCE(p.status, '') AS payment_status,
    COALESCE(s.status, '') AS shipping_status
FROM eshop_orders AS o
LEFT JOIN LATERAL (
    SELECT ep.status
    FROM eshop_payments AS ep
    WHERE ep.order_id = o.id
      AND ep.deleted_at IS NULL
    ORDER BY ep.created_at DESC
    LIMIT 1
) AS p ON TRUE
LEFT JOIN LATERAL (
    SELECT sl.status
    FROM eshop_shipping_labels AS sl
    WHERE sl.order_id = o.id
      AND sl.deleted_at IS NULL
    ORDER BY sl.created_at DESC
    LIMIT 1
) AS s ON TRUE
WHERE o.deleted_at IS NULL
ORDER BY o.created_at DESC
LIMIT $1;

-- name: SummarizeOrderRevenue :one
SELECT
    COUNT(*)::bigint AS order_count,
    COALESCE(SUM(total_amount_cents), 0)::bigint AS gross_revenue_cents,
    COALESCE(SUM(shipping_price_cents), 0)::bigint AS shipping_revenue_cents
FROM eshop_orders
WHERE deleted_at IS NULL
  AND created_at >= $1
  AND created_at < $2;

-- name: ListOrderStatusBreakdown :many
SELECT
    status,
    COUNT(*)::bigint AS order_count
FROM eshop_orders
WHERE deleted_at IS NULL
GROUP BY status
ORDER BY order_count DESC, status ASC;
