package tencentrtc

import (
	"testing"
	"time"
)

// TestGenerateTokenUsesInternalUserIDAndStringRoomID verifies the Phase 2 mapping contract.
func TestGenerateTokenUsesInternalUserIDAndStringRoomID(t *testing.T) {
	now := time.Unix(1_700_000_000, 0)

	result, err := GenerateToken(TokenConfig{
		Enabled:    true,
		SDKAppID:   1400000000,
		SecretKey:  "secret",
		TTL:        2 * time.Hour,
		RoomIDType: RoomIDTypeString,
		AppScene:   AppSceneVoiceChatRoom,
	}, 10001, "room_1001", now)
	if err != nil {
		t.Fatalf("GenerateToken failed: %v", err)
	}

	if result.UserID != "10001" || result.RTCUserID != "10001" {
		t.Fatalf("rtc user id mismatch: %+v", result)
	}
	if result.RoomID != "room_1001" || result.StrRoomID != "room_1001" || result.RTCRoomIDType != RoomIDTypeString {
		t.Fatalf("rtc room id mismatch: %+v", result)
	}
	if result.Role != RoleAudience || result.AppScene != AppSceneVoiceChatRoom {
		t.Fatalf("rtc policy mismatch: %+v", result)
	}
	if result.UserSig == "" || result.ExpireAtMS != now.Add(2*time.Hour).UnixMilli() {
		t.Fatalf("usersig fields mismatch: %+v", result)
	}
}

// TestGenerateTokenFailsClosed verifies disabled or unsupported RTC config never signs.
func TestGenerateTokenFailsClosed(t *testing.T) {
	_, err := GenerateToken(TokenConfig{
		Enabled:    false,
		SDKAppID:   1400000000,
		SecretKey:  "secret",
		TTL:        time.Hour,
		RoomIDType: RoomIDTypeString,
		AppScene:   AppSceneVoiceChatRoom,
	}, 10001, "room_1001", time.Unix(1_700_000_000, 0))
	if err == nil {
		t.Fatalf("GenerateToken should reject disabled rtc config")
	}

	_, err = GenerateToken(TokenConfig{
		Enabled:    true,
		SDKAppID:   1400000000,
		SecretKey:  "secret",
		TTL:        time.Hour,
		RoomIDType: "number",
		AppScene:   AppSceneVoiceChatRoom,
	}, 10001, "room_1001", time.Unix(1_700_000_000, 0))
	if err == nil {
		t.Fatalf("GenerateToken should reject unsupported room_id_type")
	}
}

func TestGenerateTokenRejectsInvalidRoomID(t *testing.T) {
	_, err := GenerateToken(TokenConfig{
		Enabled:    true,
		SDKAppID:   1400000000,
		SecretKey:  "secret",
		TTL:        time.Hour,
		RoomIDType: RoomIDTypeString,
		AppScene:   AppSceneVoiceChatRoom,
	}, 10001, "room:1001", time.Unix(1_700_000_000, 0))
	if err == nil {
		t.Fatalf("GenerateToken should reject invalid room_id")
	}
}
