/**
 * 数据库功能测试脚本
 * 直接测试 Prisma 操作，绕过认证
 */

import { prisma } from './db/client.js';

async function testDatabase() {
  console.log('🧪 测试数据库功能\n');

  const testUserId = 'test-user-' + Date.now();

  try {
    // 1. 创建用户
    console.log('1️⃣ 创建测试用户...');
    const user = await prisma.user.create({
      data: {
        id: testUserId,
        name: '测试用户'
      }
    });
    console.log('   ✅ 用户创建成功:', user.id);

    // 2. 创建用户设置
    console.log('\n2️⃣ 创建用户设置...');
    const settings = await prisma.userSettings.create({
      data: {
        userId: testUserId,
        targetLanguage: 'chinese',
        translationConcurrency: 15
      }
    });
    console.log('   ✅ 设置创建成功:', settings.id);

    // 3. 创建文档
    console.log('\n3️⃣ 创建文档...');
    const document = await prisma.document.create({
      data: {
        userId: testUserId,
        fileName: 'test-paper.pdf',
        fileType: 'pdf',
        status: 'PENDING'
      }
    });
    console.log('   ✅ 文档创建成功:', document.id);

    // 4. 创建术语库
    console.log('\n4️⃣ 创建术语库...');
    const glossary = await prisma.glossary.create({
      data: {
        userId: testUserId,
        name: '测试术语库',
        entries: [
          { source: 'AI', target: '人工智能' },
          { source: 'ML', target: '机器学习' }
        ]
      }
    });
    console.log('   ✅ 术语库创建成功:', glossary.id);

    // 5. 创建聊天消息
    console.log('\n5️⃣ 创建聊天消息...');
    const chatMessage = await prisma.chatMessage.create({
      data: {
        documentId: document.id,
        userId: testUserId,
        role: 'user',
        content: '这篇论文的主要贡献是什么？'
      }
    });
    console.log('   ✅ 聊天消息创建成功:', chatMessage.id);

    // 6. 查询测试
    console.log('\n6️⃣ 查询测试...');
    const userWithRelations = await prisma.user.findUnique({
      where: { id: testUserId },
      include: {
        settings: true,
        documents: true,
        glossaries: true,
        chatMessages: true
      }
    });
    console.log('   ✅ 查询结果:');
    console.log('      - 设置:', userWithRelations.settings ? '有' : '无');
    console.log('      - 文档数:', userWithRelations.documents.length);
    console.log('      - 术语库数:', userWithRelations.glossaries.length);
    console.log('      - 聊天消息数:', userWithRelations.chatMessages.length);

    // 7. 清理测试数据
    console.log('\n7️⃣ 清理测试数据...');
    await prisma.chatMessage.deleteMany({ where: { userId: testUserId } });
    await prisma.document.deleteMany({ where: { userId: testUserId } });
    await prisma.glossary.deleteMany({ where: { userId: testUserId } });
    await prisma.userSettings.deleteMany({ where: { userId: testUserId } });
    await prisma.user.delete({ where: { id: testUserId } });
    console.log('   ✅ 测试数据已清理');

    console.log('\n✅ 所有数据库测试通过！\n');

  } catch (error) {
    console.error('\n❌ 测试失败:', error.message);
    console.error(error);
    process.exit(1);
  } finally {
    await prisma.$disconnect();
  }
}

testDatabase();