// testDataImporter.ts
import { CloudObject, CloudUser } from './ncloud';

// 创建测试用户
async function createTestUsers(): Promise<CloudUser[]> {
    const users = [
        { username: 'user1', password: '123456', email: 'user1@example.com' },
        { username: 'user2', password: '123456', email: 'user2@example.com' },
        { username: 'user3', password: '123456', email: 'user3@example.com' }
    ];

    const createdUsers: CloudUser[] = [];
    for (const userData of users) {
        const user = new CloudUser();
        const existing = await user.login(userData.username, userData.password);
        if (!existing) {
            await user.signUp(userData.username, userData.password, {
                email: userData.email,
                profilePicture: `https://randomuser.me/api/portraits/${Math.random() > 0.5 ? 'men' : 'women'}/${Math.floor(Math.random() * 50)}.jpg`
            });
        }
        createdUsers.push(user);
        console.log(`User created: ${user.id}`);
    }
    return createdUsers;
}

// 创建测试动态（表名改为Dynamic）
async function createTestDynamics(users: CloudUser[]): Promise<CloudObject[]> {
    const dynamics = [
        {
            content: "今天天气真好，去公园散步了！🌞",
            images: ["https://example.com/park1.jpg", "https://example.com/park2.jpg"],
            location: { latitude: 39.9042, longitude: 116.4074 },
            mood: "happy",
            tags: ["户外", "休闲"]
        },
        {
            content: "刚学会用PostgreSQL，太强大了！💪",
            images: [],
            mood: "excited",
            tags: ["学习", "编程"]
        },
        {
            content: "分享一首好听的歌：https://music.163.com/song?id=123456",
            images: ["https://example.com/music_cover.jpg"],
            mood: "relaxed",
            tags: ["音乐", "分享"]
        }
    ];

    const createdDynamics: CloudObject[] = [];
    for (const dynamicData of dynamics) {
        const dynamic = new CloudObject("Dynamic");  // 修改为Dynamic
        dynamic.set({
            ...dynamicData,
            isPublic: true,
            author: users[Math.floor(Math.random() * users.length)].toPointer()
        });
        await dynamic.save();
        createdDynamics.push(dynamic);
        console.log(`Dynamic created: ${dynamic.id}`);
    }
    return createdDynamics;
}

// 创建测试互动（关联Dynamic表）
async function createTestInteractions(users: CloudUser[], dynamics: CloudObject[]) {
    const interactionTypes = ['like', 'comment', 'share'];
    const comments = [
        "太棒了！",
        "我也想去！",
        "感谢分享！",
        "有意思 😄",
        "学到了新知识"
    ];

    // 每个动态生成3-5个互动
    for (const dynamic of dynamics) {
        const interactionCount = 3 + Math.floor(Math.random() * 3);
        
        for (let i = 0; i < interactionCount; i++) {
            const interaction = new CloudObject("Interaction");
            const user = users[Math.floor(Math.random() * users.length)];
            const type = interactionTypes[Math.floor(Math.random() * interactionTypes.length)];
            
            const interactionData: any = {
                type,
                user: user.toPointer(),
                dynamic: dynamic.toPointer()  // 字段名改为dynamic
            };

            if (type === 'comment') {
                interactionData.content = comments[Math.floor(Math.random() * comments.length)];
            } else if (type === 'share') {
                interactionData.targetUser = users.find(u => u.id !== user.id)?.toPointer();
            }

            interaction.set(interactionData);
            await interaction.save();
            console.log(`Interaction created: ${interaction.id} (${type})`);

            // 更新动态的计数器
            const dynamicUpdate = new CloudObject("Dynamic");  // 修改为Dynamic
            dynamicUpdate.id = dynamic.id;
            dynamicUpdate.set({
                [`${type}Count`]: { __op: "Increment", amount: 1 }
            });
            await dynamicUpdate.save();
        }
    }
}

// 主执行函数
export async function importTestData() {
    try {
        console.log("Starting test data import...");
        
        // 1. 创建测试用户
        console.log("Creating test users...");
        const users = await createTestUsers();
        
        // 2. 创建测试动态
        console.log("Creating test dynamics...");
        const dynamics = await createTestDynamics(users);
        
        // 3. 创建互动数据
        console.log("Creating test interactions...");
        await createTestInteractions(users, dynamics);
        
        console.log("Test data import completed successfully!");
    } catch (error) {
        console.error("Error during test data import:", error);
    }
} 