package service

import (
	"context"
	"encoding/json"

	"wucher/internal/queue"
)

type EmailJob = queue.EmailJob

type EmailQueue = queue.EmailJobProducer

func EncodeEmailJob(job EmailJob) ([]byte, error) {
	return json.Marshal(job.Canonical())
}

func DecodeEmailJob(b []byte) (*EmailJob, error) {
	var job EmailJob
	if err := json.Unmarshal(b, &job); err != nil {
		return nil, err
	}
	job = job.Canonical()
	if err := job.Validate(); err != nil {
		return nil, err
	}
	return &job, nil
}

type emailQueueAdapter struct {
	producer queue.EmailJobProducer
}

func (a emailQueueAdapter) Enqueue(ctx context.Context, job EmailJob) error {
	return a.producer.Enqueue(ctx, job)
}

func AdaptEmailQueue(producer queue.EmailJobProducer) EmailQueue {
	if producer == nil {
		return nil
	}
	return emailQueueAdapter{producer: producer}
}
