package internal

import (
	"encoding/json"
	"fmt"
	"github.com/streadway/amqp"
	"golang.source-fellows.com/pattern/saga/internal/model"
)

func StartRegistrationService(ch *amqp.Channel) {

	registrationReplyMsgs, err := ch.Consume(
		RegistrationReplyQueueName, // Queue-Name
		"",                         // Consumer
		true,                       // Auto-Ack
		false,                      // Exclusive
		false,                      // No-local
		false,                      // No-Wait
		nil,                        // Args
	)
	FailOnError(err, "Failed to register consumer")

	go func() {
		for d := range registrationReplyMsgs {

			registrationResponse := model.RegistrationResponse{}
			err := json.Unmarshal(d.Body, &registrationResponse)
			FailOnError(err, "could not unmarshal json")

			fmt.Printf("RegistrationService: Received RegistrationResponse for Training %+v\n", registrationResponse)

			reply := model.CustomerNotification{}
			bytes, err := json.Marshal(reply)
			FailOnError(err, "could not marshal json")

			// Simuliere erfolgreiche Buchung
			err = ch.Publish(
				"",                            // Exchange
				CustomerNotificationQueueName, // Routing Key
				false,
				false,
				amqp.Publishing{
					ContentType: "application/json",
					Body:        bytes,
				},
			)
			FailOnError(err, "Failed to publish CustomerNotification")
			fmt.Printf("RegistrationService: Published CustomerNotification for %+v\n", reply)
		}
	}()
}

func SendRegistration(ch *amqp.Channel) {
	// Simuliere eine neue Bestellung
	newRegistrationRequest := model.RegistrationRequest{}
	bytes, err := json.Marshal(newRegistrationRequest)
	FailOnError(err, "could not marshal json")
	err = ch.Publish(
		"",
		NewRegistrationQueueName,
		false,
		false,
		amqp.Publishing{
			ContentType: "application/json",
			Body:        bytes,
		},
	)
	FailOnError(err, "Failed to publish OrderCreated")
	fmt.Printf("Main: Published Registration %+v\n", newRegistrationRequest)
}
