package service_test

import (
	"context"
	"testing"
	"time"

	roomv1 "hyapp.local/api/proto/room/v1"
	"hyapp/pkg/appcode"
	"hyapp/services/room-service/internal/integration"
	roomservice "hyapp/services/room-service/internal/room/service"
	"hyapp/services/room-service/internal/router"
	"hyapp/services/room-service/internal/testutil/mysqltest"
)

func TestJoinRoomAcceptsRoomShortIDWithoutWritingShortIDCommandLog(t *testing.T) {
	ctx := context.Background()
	repository := mysqltest.NewRepository(t)
	svc := roomservice.New(roomservice.Config{
		NodeID:         "node-short-id-join-test",
		LeaseTTL:       10 * time.Second,
		RankLimit:      20,
		SnapshotEveryN: 1,
	}, router.NewMemoryDirectory(), repository, followTestWallet{}, integration.NewNoopRoomEventPublisher(), integration.NewNoopOutboxPublisher())

	roomID := "room-short-id-join"
	roomShortID := "167822"
	ownerID := int64(6101)
	viewerID := int64(6102)
	if _, err := svc.CreateRoom(ctx, &roomv1.CreateRoomRequest{
		Meta:            roomservice.NewRequestMeta(roomID, ownerID),
		SeatCount:       10,
		Mode:            "voice",
		VisibleRegionId: 6101,
		RoomName:        "Short ID Join",
		RoomAvatar:      testRoomCoverURL,
		RoomShortId:     roomShortID,
	}); err != nil {
		t.Fatalf("create room: %v", err)
	}

	joinMeta := roomservice.NewRequestMeta(roomShortID, viewerID)
	joinMeta.CommandId = "cmd-join-by-room-short-id"
	resp, err := svc.JoinRoom(ctx, &roomv1.JoinRoomRequest{
		Meta: joinMeta,
		Role: "audience",
	})
	if err != nil {
		t.Fatalf("join room by short id: %v", err)
	}
	if resp.GetRoom().GetRoomId() != roomID || resp.GetRoom().GetRoomShortId() != roomShortID {
		t.Fatalf("join response must expose canonical room id and short id, got %+v", resp.GetRoom())
	}

	repoCtx := appcode.WithContext(context.Background(), appcode.Default)
	if _, exists, err := repository.GetCommand(repoCtx, roomID, joinMeta.GetCommandId()); err != nil || !exists {
		t.Fatalf("join command must be written under canonical room id, exists=%v err=%v", exists, err)
	}
	if _, exists, err := repository.GetCommand(repoCtx, roomShortID, joinMeta.GetCommandId()); err != nil || exists {
		t.Fatalf("short id must not create an independent command log partition, exists=%v err=%v", exists, err)
	}
}
