import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

async function cleanup() {
  console.log('Checking all rounds...\n')

  const rounds = await prisma.round.findMany({
    select: {
      id: true,
      name: true,
      slug: true,
      projects: { select: { id: true, title: true } },
      _count: { select: { projects: true } }
    }
  })

  console.log(`Found ${rounds.length} rounds:`)
  for (const round of rounds) {
    console.log(`- ${round.name} (slug: ${round.slug}): ${round._count.projects} projects`)
  }

  // Find rounds with 9 or fewer projects (dummy data)
  const dummyRounds = rounds.filter(r => r._count.projects <= 9)

  if (dummyRounds.length > 0) {
    console.log(`\nDeleting ${dummyRounds.length} dummy round(s)...`)

    for (const round of dummyRounds) {
      console.log(`\nProcessing: ${round.name}`)

      const projectIds = round.projects.map(p => p.id)

      if (projectIds.length > 0) {
        // Delete team members
        const teamDeleted = await prisma.teamMember.deleteMany({
          where: { projectId: { in: projectIds } }
        })
        console.log(`  Deleted ${teamDeleted.count} team members`)

        // Delete projects
        const projDeleted = await prisma.project.deleteMany({
          where: { id: { in: projectIds } }
        })
        console.log(`  Deleted ${projDeleted.count} projects`)
      }

      // Delete the round
      await prisma.round.delete({ where: { id: round.id } })
      console.log(`  Deleted round: ${round.name}`)
    }
  }

  // Summary
  const remaining = await prisma.round.count()
  const projects = await prisma.project.count()
  console.log(`\n✅ Cleanup complete!`)
  console.log(`   Remaining rounds: ${remaining}`)
  console.log(`   Total projects: ${projects}`)
}

cleanup()
  .then(() => prisma.$disconnect())
  .catch(async (e) => {
    console.error(e)
    await prisma.$disconnect()
    process.exit(1)
  })
