package api

import (
	"context"
	"encoding/json"
	"fmt"

	"deevirt.fr/compute/pkg/amqp"
	"deevirt.fr/compute/pkg/api/proto"
	"libvirt.org/go/libvirt"
)

type Events struct {
	NodeID       string
	CompanyID    string
	DatacenterID string
	DomainID     string
	Event        *libvirt.DomainQemuMonitorEvent
}

func (d *Domain) Event(ctx context.Context, req *proto.DomainEventRequest) (*proto.DomainEventResponse, error) {
	var events Events

	err := json.Unmarshal(req.Event, &events)
	if err != nil {
		fmt.Println("Erreur lors du décodage JSON:", err)
	}

	// AMQP - On envoi l'évènement brut
	e, _ := json.Marshal(events.Event)
	a, _ := amqp.NewAMQP()
	a.Publisher("vmcenter",
		"events."+events.CompanyID+
			"."+events.DatacenterID+
			"."+events.DomainID,
		e)
	defer a.Close()

	t, _ := json.Marshal(events)

	fmt.Printf("%v\n", string(t))

	return &proto.DomainEventResponse{}, nil
}
