package queue

import (
	"context"
	"testing"
)

func TestJSONSerializerRoundTrip(t *testing.T) {
	serializer := NewJSONSerializer("v1", true, QueueTypeStandard, "")
	ctx := WithCorrelationID(context.Background(), "req-123")
	message, err := serializer.Serialize(ctx, EmailJob{
		Type:     "invite_set_password",
		To:       "user@example.com",
		Subject:  "Welcome",
		Body:     "hello",
		HTMLBody: "<b>hello</b>",
	})
	if err != nil {
		t.Fatalf("serialize: %v", err)
	}

	envelope, err := serializer.Deserialize(message.Body, message.Attributes)
	if err != nil {
		t.Fatalf("deserialize: %v", err)
	}
	if envelope.MessageID == "" {
		t.Fatalf("expected message id")
	}
	if envelope.CorrelationID != "req-123" {
		t.Fatalf("expected correlation id req-123, got %q", envelope.CorrelationID)
	}
	if envelope.Payload.NormalizedType() != "invite_set_password" {
		t.Fatalf("unexpected job type: %q", envelope.Payload.NormalizedType())
	}
}

func TestJSONSerializerLegacyFallback(t *testing.T) {
	serializer := NewJSONSerializer("v1", true, QueueTypeStandard, "")
	envelope, err := serializer.Deserialize([]byte(`{"to":"user@example.com","subject":"Reset","body":"hello"}`), map[string]string{
		"correlation_id": "legacy-1",
	})
	if err != nil {
		t.Fatalf("deserialize legacy: %v", err)
	}
	if envelope.Version != "legacy" {
		t.Fatalf("expected legacy version, got %q", envelope.Version)
	}
	if envelope.CorrelationID != "legacy-1" {
		t.Fatalf("unexpected correlation id: %q", envelope.CorrelationID)
	}
	if envelope.Payload.To != "user@example.com" {
		t.Fatalf("unexpected payload: %+v", envelope.Payload)
	}
}
