package com.smyhub.store.mengyastorebackendjava.mq;

import com.smyhub.store.mengyastorebackendjava.config.AppProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class OrderEmailProducer {

    private final RabbitTemplate rabbitTemplate;
    private final AppProperties appProperties;

    /**
     * Publishes an order email payload to RabbitMQ.
     * Returns true on success, false on failure (caller should fall back to direct email).
     */
    public boolean publish(OrderEmailPayload payload) {
        if (!appProperties.isRabbitmqEnabled()) {
            return false;
        }
        String exchange = RabbitMQTopology.exchangeName(appProperties.getRabbitmqEnv());
        try {
            rabbitTemplate.convertAndSend(exchange, RabbitMQTopology.ORDER_EMAIL_ROUTING_KEY, payload);
            log.info("[MQ] queued order email order={} to={}", payload.getOrderId(), payload.getToEmail());
            return true;
        } catch (AmqpException e) {
            log.warn("[MQ] publish failed, will fallback to direct email: {}", e.getMessage());
            return false;
        }
    }
}
