package com.luojia_channel.modules.feedback.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FeedbackRabbitMQConfig {

    // 反馈工单交换机
    public static final String FEEDBACK_EXCHANGE = "feedback.exchange";

    // 延迟队列 - 消息先进入此队列，过期后转发到死信队列
    public static final String FEEDBACK_DELAY_QUEUE = "feedback.delay.queue";

    // 死信交换机 - 延迟队列的死信会转发到此交换机
    public static final String FEEDBACK_DLX_EXCHANGE = "feedback.dlx.exchange";

    // 死信队列 - 最终消费者监听此队列
    public static final String FEEDBACK_DLX_QUEUE = "feedback.dlx.queue";

    // 路由键
    public static final String FEEDBACK_ROUTING_KEY = "feedback.routing.key";

    // 声明反馈交换机
    @Bean
    DirectExchange feedbackExchange() {
        return new DirectExchange(FEEDBACK_EXCHANGE, true, false);
    }

    // 声明死信交换机
    @Bean
    DirectExchange feedbackDlxExchange() {
        return new DirectExchange(FEEDBACK_DLX_EXCHANGE, true, false);
    }

    // 声明延迟队列，并绑定到死信交换机
    @Bean
    Queue feedbackDelayQueue() {
        return QueueBuilder.durable(FEEDBACK_DELAY_QUEUE)
                .withArgument("x-dead-letter-exchange", FEEDBACK_DLX_EXCHANGE)
                .withArgument("x-dead-letter-routing-key", FEEDBACK_ROUTING_KEY)
                .build();
    }

    // 声明死信队列
    @Bean
    Queue feedbackDlxQueue() {
        return new Queue(FEEDBACK_DLX_QUEUE, true);
    }

    // 绑定延迟队列到反馈交换机
    @Bean
    Binding feedbackDelayBinding() {
        return BindingBuilder.bind(feedbackDelayQueue())
                .to(feedbackExchange())
                .with(FEEDBACK_ROUTING_KEY);
    }

    // 绑定死信队列到死信交换机
    @Bean
    Binding feedbackDlxBinding() {
        return BindingBuilder.bind(feedbackDlxQueue())
                .to(feedbackDlxExchange())
                .with(FEEDBACK_ROUTING_KEY);
    }
}