const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

async function checkDatabase() {
  try {
    console.log('📊 查询 bookId=1 的所有章节记录...\n');
    
    const chapters = await prisma.bookChapter.findMany({
      where: { bookId: 1 },
      orderBy: [
        { level: 'asc' },
        { number: 'asc' }
      ]
    });

    console.log(`总记录数: ${chapters.length}\n`);

    // 按级别统计
    const level1 = chapters.filter(c => c.level === 1);
    const level2 = chapters.filter(c => c.level === 2);
    const level3 = chapters.filter(c => c.level === 3);

    console.log(`章 (level=1): ${level1.length} 条`);
    console.log(`节 (level=2): ${level2.length} 条`);
    console.log(`小节 (level=3): ${level3.length} 条\n`);

    // 显示前5条记录
    console.log('前5条记录:');
    chapters.slice(0, 5).forEach(c => {
      console.log(`  ID=${c.id}, level=${c.level}, number=${c.number}, parentId=${c.parentId}, title=${c.title}`);
    });

    // 检查是否有重复
    console.log('\n检查重复 (bookId, parentId, level, number):');
    const keyMap = new Map();
    chapters.forEach(c => {
      const key = `${c.bookId}_${c.parentId}_${c.level}_${c.number}`;
      if (keyMap.has(key)) {
        console.log(`  ⚠️  重复: ${key}`);
        console.log(`     记录1: ID=${keyMap.get(key)}, title=${chapters.find(x => x.id === keyMap.get(key))?.title}`);
        console.log(`     记录2: ID=${c.id}, title=${c.title}`);
      } else {
        keyMap.set(key, c.id);
      }
    });

    console.log('\n✅ 检查完成');

  } catch (error) {
    console.error('错误:', error);
  } finally {
    await prisma.$disconnect();
  }
}

checkDatabase();
