package internal

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

func StartAdministrationService(ch *amqp.Channel) {
	newRegistrationMsgs, err := ch.Consume(
		NewRegistrationQueueName, // 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 newRegistrationMsgs {

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

			fmt.Printf("AdministrationService: Received RegistrationRequest for Training %+v\n", registrationRequest)

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

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