package rabbitmq

import (
	"encoding/json"
	"fmt"

	"git.umbach.dev/app-idea/rest-api/modules/config"
	"git.umbach.dev/app-idea/rest-api/modules/structs"
	log "github.com/sirupsen/logrus"
	"github.com/streadway/amqp"
)

var Conn *amqp.Connection
var MailQueue amqp.Queue
var Channel *amqp.Channel

func getConnectionString() string {
	cfg := &config.Cfg.RabbitMq

	return fmt.Sprintf("amqp://%s:%s@%s/", cfg.Username, cfg.Password, cfg.Host)
}

func Init() {
	conn, err := amqp.Dial(getConnectionString())

	if err != nil {
		log.Fatalln("Failed to connect to RabbitMQ", err)
	}

	Conn = conn

	ch, err := conn.Channel()

	if err != nil {
		log.Fatalln("Failed to open a channel", err)
	}

	//defer ch.Close()

	Channel = ch

	log.Debug("RabbitMQ connected")

	q, err := ch.QueueDeclare(
		"mails", // name
		false,   // durable
		false,   // delete when unused
		false,   // exclusive
		false,   // no-wait
		nil,     // arguments
	)

	if err != nil {
		log.Fatalln("Failed to declare a queue", err)
	}

	MailQueue = q
}

func Publish(body string) {
	log.Infoln("qu name", MailQueue.Name)
	log.Infoln("publish", Channel, MailQueue)

	err := Channel.Publish(
		"",             // exchange
		MailQueue.Name, // routing key
		false,          // mandatory
		false,          // immediate
		amqp.Publishing{
			ContentType: "application/json",
			Body:        []byte(body),
		})

	if err != nil {
		log.Fatalln("Failed to publish a message", err)
	}
}

func PublishMail(mail string, templateId int, languageId int, bodyData json.RawMessage) {
	js := structs.RabbitmqMailMessage{Mail: mail, TemplateId: templateId, LanguageId: languageId, BodyData: &bodyData}

	reqBody, err := json.MarshalIndent(&js, "", "\t")

	if err != nil {
		log.Infoln("error reqBody", err)
	}

	Publish(string(reqBody))
}
