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

const prisma = new PrismaClient()

async function cleanDuplicateUsers() {
  try {
    console.log('Cleaning duplicate users that exist in both users and tenants tables...')

    // Find users that exist in both tables
    const duplicateUsers = await prisma.user.findMany({
      where: {
        role: 'tenant'
      },
      select: {
        id: true,
        email: true,
        firstName: true,
        lastName: true,
        role: true
      }
    })

    console.log(`Found ${duplicateUsers.length} users with role 'tenant' in users table`)

    // Check which of these also exist in tenants table
    const usersToRemove = []

    for (const user of duplicateUsers) {
      const tenantExists = await prisma.tenant.findFirst({
        where: {
          email: user.email
        }
      })

      if (tenantExists) {
        usersToRemove.push(user)
        console.log(`Will remove user: ${user.email} (exists in both tables)`)
      }
    }

    // Remove duplicate users from users table
    for (const user of usersToRemove) {
      await prisma.user.delete({
        where: { id: user.id }
      })
      console.log(`✅ Removed duplicate user: ${user.email}`)
    }

    console.log(`\n✅ Cleaned up ${usersToRemove.length} duplicate users`)
    console.log('Now tenants should be able to login properly!')

  } catch (error) {
    console.error('Error cleaning duplicate users:', error)
  } finally {
    await prisma.$disconnect()
  }
}

cleanDuplicateUsers()