package mysql

import (
	"context"
	"testing"

	"hyapp/pkg/appcode"
)

func TestGetRoomMetaByShortIDReturnsCanonicalRoomID(t *testing.T) {
	ctx := appcode.WithContext(context.Background(), appcode.Default)
	repo := newCommandLogTestRepository(t, ctx)
	insertCommandLogTestRoom(t, ctx, repo, "room-meta-short")

	meta, exists, err := repo.GetRoomMetaByShortID(ctx, " room-meta-short-short ")
	if err != nil {
		t.Fatalf("get room meta by short id: %v", err)
	}
	if !exists {
		t.Fatal("room short id should resolve existing room meta")
	}
	if meta.RoomID != "room-meta-short" || meta.RoomShortID != "room-meta-short-short" {
		t.Fatalf("short id must return canonical room meta, got %+v", meta)
	}
}

func TestGetRoomMetaByGlobalIDResolvesOwningApp(t *testing.T) {
	ctx := context.Background()
	repo := newCommandLogTestRepository(t, ctx)
	if _, err := repo.db.ExecContext(ctx, `
		INSERT INTO rooms (
		  app_code, room_id, room_short_id, owner_user_id, seat_count, mode, status,
		  visible_region_id, created_at_ms, updated_at_ms
		) VALUES ('fami', 'room-fami-rtc', 'fami-rtc', 9001, 8, 'voice', 'active', 1, 1000, 1000)`); err != nil {
		t.Fatalf("insert fami room: %v", err)
	}

	meta, exists, err := repo.GetRoomMetaByGlobalID(appcode.WithContext(ctx, "lalu"), "room-fami-rtc")
	if err != nil || !exists {
		t.Fatalf("resolve global room app: exists=%t err=%v", exists, err)
	}
	if meta.AppCode != "fami" || meta.RoomID != "room-fami-rtc" {
		t.Fatalf("global room lookup must ignore caller default app and return owner: %+v", meta)
	}
}
