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

const prisma = new PrismaClient()

async function setTenantPasswords() {
  try {
    console.log('Setting default passwords for tenants without password hashes...')

    // Find all tenants without password hashes
    const tenantsWithoutPasswords = await prisma.tenant.findMany({
      where: {
        passwordHash: null,
        deletedAt: null,
        email: {
          not: null
        }
      },
      select: {
        id: true,
        firstName: true,
        lastName: true,
        email: true
      }
    })

    console.log(`Found ${tenantsWithoutPasswords.length} tenants without passwords`)

    const defaultPassword = 'password123' // You should change this to a secure default
    const hashedPassword = await bcrypt.hash(defaultPassword, 12)

    for (const tenant of tenantsWithoutPasswords) {
      await prisma.tenant.update({
        where: { id: tenant.id },
        data: { passwordHash: hashedPassword }
      })
      console.log(`Set password for tenant: ${tenant.firstName} ${tenant.lastName} (${tenant.email})`)
    }

    console.log('✅ All tenants now have password hashes set')
    console.log(`Default password for tenants: ${defaultPassword}`)
    console.log('⚠️  Please change this default password immediately for security!')

  } catch (error) {
    console.error('Error setting tenant passwords:', error)
  } finally {
    await prisma.$disconnect()
  }
}

setTenantPasswords()