package com.zioinfo.mall.realtime;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zioinfo.mall.order.MallOrder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 주문 이벤트 발행기 — 신규 주문/상태 변경을 WebSocket으로 브로드캐스트.
 * 관리자앱 Live Order Dashboard가 구독한다. 직렬화 실패는 무시(주문 흐름 차단 금지).
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class OrderNotifier {

    private final OrderWebSocketHandler handler;
    private final ObjectMapper objectMapper = new ObjectMapper();

    public void broadcastNewOrder(MallOrder order) {
        emit("ORDER_NEW", order);
    }

    public void broadcastStatus(MallOrder order) {
        emit("ORDER_STATUS", order);
    }

    private void emit(String event, MallOrder order) {
        try {
            Map<String, Object> payload = new LinkedHashMap<>();
            payload.put("event", event);
            payload.put("orderNo", order.getOrderNo());
            payload.put("storeId", order.getStoreId());
            payload.put("status", order.getStatus());
            payload.put("fulfillmentType", order.getFulfillmentType());
            payload.put("scheduledDate", order.getScheduledDate());
            payload.put("slotLabel", order.getSlotLabel());
            payload.put("payAmount", order.getPayAmount());
            payload.put("receiverName", order.getReceiverName());
            handler.broadcast(objectMapper.writeValueAsString(payload));
        } catch (Exception e) {
            log.warn("주문 이벤트 발행 실패(무시): {}", e.getMessage());
        }
    }
}
