package mq

import (
	"fmt"
	"strings"

	amqp "github.com/rabbitmq/amqp091-go"
)

const routingKeyOrderEmail = "order.email.notify"

// OrderEmailRoutingKey 订单通知消息的绑定键 / 发布 routing key。
func OrderEmailRoutingKey() string { return routingKeyOrderEmail }

// ExchangeName 返回本应用 + 环境对应的持久化 topic 交换机名（与 Broker 上其它应用隔离）。
func ExchangeName(env string) string {
	return fmt.Sprintf("ex.mengyastore.%s.events", sanitizeEnv(env))
}

// QueueName 返回本环境下持久化的订单邮件队列名。
func QueueName(env string) string {
	return fmt.Sprintf("q.mengyastore.%s.order_email", sanitizeEnv(env))
}

func sanitizeEnv(env string) string {
	e := strings.TrimSpace(strings.ToLower(env))
	if e == "prod" || e == "production" {
		return "prod"
	}
	return "dev"
}

func declareTopology(ch *amqp.Channel, env string) (exchange, queue string, err error) {
	exchange = ExchangeName(env)
	queue = QueueName(env)

	if err = ch.ExchangeDeclare(
		exchange,
		"topic",
		true,
		false,
		false,
		false,
		nil,
	); err != nil {
		return "", "", fmt.Errorf("exchange declare: %w", err)
	}

	if _, err = ch.QueueDeclare(
		queue,
		true,
		false,
		false,
		false,
		nil,
	); err != nil {
		return "", "", fmt.Errorf("queue declare: %w", err)
	}

	if err = ch.QueueBind(
		queue,
		routingKeyOrderEmail,
		exchange,
		false,
		nil,
	); err != nil {
		return "", "", fmt.Errorf("queue bind: %w", err)
	}

	return exchange, queue, nil
}
