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,
      roundProjects: { select: { id: true, projectId: true, project: { select: { id: true, title: true } } } },
      _count: { select: { roundProjects: true } }
    }
  })

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

  // Find rounds with 9 or fewer projects (dummy data)
  const dummyRounds = rounds.filter(r => r._count.roundProjects <= 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.roundProjects.map(rp => rp.projectId)

      if (projectIds.length > 0) {
        // Delete round-project associations first
        const rpDeleted = await prisma.roundProject.deleteMany({
          where: { roundId: round.id }
        })
        console.log(`  Deleted ${rpDeleted.count} round-project associations`)

        // 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)
  })
