package integration

import (
	"testing"

	roomeventsv1 "hyapp.local/api/proto/events/room/v1"
	"hyapp/pkg/roommq"
)

func TestRoomOutboxRocketMessageUsesConfiguredTagMode(t *testing.T) {
	tests := []struct {
		name    string
		mode    roommq.EventTagMode
		wantTag string
	}{
		{name: "missing config remains legacy", mode: "", wantTag: roommq.TagRoomOutboxEvent},
		{name: "phase a publishes legacy", mode: roommq.EventTagModeLegacy, wantTag: roommq.TagRoomOutboxEvent},
		{name: "phase b publishes event type", mode: roommq.EventTagModeEventType, wantTag: roommq.EventTypeRoomGiftSent},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			message, err := roomOutboxRocketMessage("hyapp_room_outbox", test.mode, validRoomOutboxEnvelope())
			if err != nil {
				t.Fatalf("roomOutboxRocketMessage failed: %v", err)
			}
			if message.Tag != test.wantTag {
				t.Fatalf("message tag = %q, want %q", message.Tag, test.wantTag)
			}
			envelope, _, err := roommq.DecodeRoomOutboxMessage(message.Body)
			if err != nil {
				t.Fatalf("DecodeRoomOutboxMessage failed: %v", err)
			}
			if envelope.GetEventType() != roommq.EventTypeRoomGiftSent {
				t.Fatalf("body event_type = %q", envelope.GetEventType())
			}
			if message.Topic != "hyapp_room_outbox" || len(message.Keys) != 2 {
				t.Fatalf("message routing metadata mismatch: %+v", message)
			}
		})
	}
}

func TestRoomOutboxRocketMessageRejectsUnsupportedModeOrUnsafeTag(t *testing.T) {
	if _, err := roomOutboxRocketMessage("hyapp_room_outbox", roommq.EventTagMode("all"), validRoomOutboxEnvelope()); err == nil {
		t.Fatal("roomOutboxRocketMessage unexpectedly accepted unsupported tag mode")
	}
	envelope := validRoomOutboxEnvelope()
	envelope.EventType = "RoomGiftSent || *"
	if _, err := roomOutboxRocketMessage("hyapp_room_outbox", roommq.EventTagModeLegacy, envelope); err == nil {
		t.Fatal("roomOutboxRocketMessage unexpectedly accepted unsafe event_type")
	}
}

func validRoomOutboxEnvelope() *roomeventsv1.EventEnvelope {
	return &roomeventsv1.EventEnvelope{
		AppCode:      "lalu",
		EventId:      "event-1",
		EventType:    "  " + roommq.EventTypeRoomGiftSent + "  ",
		RoomId:       "room-1",
		RoomVersion:  9,
		OccurredAtMs: 1_700_000_000_000,
		Body:         []byte{1, 2, 3},
	}
}
