package queue

import (
	"context"
	"log/slog"
)

type FileProcessingEnqueuer struct {
	serializer FileProcessingMessageSerializer
	producer   QueueProducer
	logger     *slog.Logger
}

func NewFileProcessingEnqueuer(serializer FileProcessingMessageSerializer, producer QueueProducer, logger *slog.Logger) *FileProcessingEnqueuer {
	if logger == nil {
		logger = slog.Default()
	}
	return &FileProcessingEnqueuer{
		serializer: serializer,
		producer:   producer,
		logger:     logger,
	}
}

func (e *FileProcessingEnqueuer) Enqueue(ctx context.Context, job FileProcessingJob) error {
	message, err := e.serializer.Serialize(ctx, job)
	if err != nil {
		return err
	}
	if err := e.producer.Publish(ctx, *message); err != nil {
		e.logger.Error("file queue publish failed",
			slog.String("backend", e.producer.Backend()),
			slog.String("message_id", message.ID),
			slog.String("file_uuid", job.Canonical().FileUUID),
			slog.String("correlation_id", message.Attributes["correlation_id"]),
			slog.Any("error", err),
		)
		return err
	}
	e.logger.Info("file queue published",
		slog.String("backend", e.producer.Backend()),
		slog.String("message_id", message.ID),
		slog.String("file_uuid", job.Canonical().FileUUID),
		slog.String("correlation_id", message.Attributes["correlation_id"]),
	)
	return nil
}
