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

async function testUpsert() {
  console.log('测试 upsert 功能（parentId=0）...\n');
  
  const bookId = 1;
  const bookIdNum = parseInt(bookId);
  
  // 先清空旧数据
  console.log('1. 清空bookId=1的旧数据...');
  await prisma.bookChapter.deleteMany({
    where: { bookId: bookIdNum }
  });
  console.log('✅ 清空完成\n');
  
  // 测试 upsert 创建章（parentId=0）
  console.log('2. 测试 upsert 创建章（parentId=0）...');
  const chapter1 = await prisma.bookChapter.upsert({
    where: {
      bookId_parentId_level_number: {
        bookId: bookIdNum,
        parentId: 0,
        level: 1,
        number: 1,
      }
    },
    update: {
      title: '第一章：测试章节（更新）',
    },
    create: {
      bookId: bookIdNum,
      parentId: 0,
      level: 1,
      number: 1,
      title: '第一章：测试章节',
      summary: '这是一个测试章节',
      status: 'completed',
    }
  });
  console.log(`✅ 创建成功: id=${chapter1.id}, parentId=${chapter1.parentId}\n`);
  
  // 再次 upsert（应该更新而不是创建）
  console.log('3. 再次 upsert（应该更新）...');
  const chapter1Updated = await prisma.bookChapter.upsert({
    where: {
      bookId_parentId_level_number: {
        bookId: bookIdNum,
        parentId: 0,
        level: 1,
        number: 1,
      }
    },
    update: {
      title: '第一章：测试章节（第二次更新）',
    },
    create: {
      bookId: bookIdNum,
      parentId: 0,
      level: 1,
      number: 1,
      title: '第一章：测试章节',
    }
  });
  console.log(`✅ 更新成功: id=${chapter1Updated.id}, title=${chapter1Updated.title}\n`);
  
  // 测试创建节（parentId=章ID）
  console.log('4. 测试创建节（parentId=章ID）...');
  const section1 = await prisma.bookChapter.upsert({
    where: {
      bookId_parentId_level_number: {
        bookId: bookIdNum,
        parentId: chapter1.id,
        level: 2,
        number: 1,
      }
    },
    update: {
      title: '第一节：测试节（更新）',
    },
    create: {
      bookId: bookIdNum,
      parentId: chapter1.id,
      level: 2,
      number: 1,
      title: '第一节：测试节',
      summary: '这是一个测试节',
      status: 'completed',
    }
  });
  console.log(`✅ 创建成功: id=${section1.id}, parentId=${section1.parentId}\n`);
  
  // 验证数据
  console.log('5. 验证数据库中的数据...');
  const allChapters = await prisma.bookChapter.findMany({
    where: { bookId: bookIdNum },
    orderBy: [
      { level: 'asc' },
      { number: 'asc' }
    ]
  });
  
  console.log(`总计 ${allChapters.length} 条记录：`);
  allChapters.forEach(c => {
    console.log(`  - id=${c.id}, level=${c.level}, parentId=${c.parentId}, number=${c.number}, title=${c.title}`);
  });
  
  // 验证没有重复
  const duplicates = await prisma.$queryRaw`
    SELECT bookId, parentId, level, number, COUNT(*) as cnt
    FROM BookChapter
    WHERE bookId = ${bookIdNum}
    GROUP BY bookId, parentId, level, number
    HAVING cnt > 1
  `;
  
  if (duplicates.length > 0) {
    console.log('\n❌ 发现重复数据：', duplicates);
  } else {
    console.log('\n✅ 没有重复数据！');
  }
  
  console.log('\n🎉 测试完成！');
  await prisma.$disconnect();
}

testUpsert().catch(err => {
  console.error('❌ 测试失败:', err);
  process.exit(1);
});
