require('dotenv').config()
const mongoose = require('mongoose')
const jwt = require('jsonwebtoken')
const { randomUUID } = require('crypto')

const BASE_URL = process.argv[2]
const EMAIL = process.argv[3] || 'jennie+cleonguyen@machinemagic.co'

if (!BASE_URL) {
  console.error('Usage: node scripts/mint-invite-link.cjs <base-url> [email]')
  process.exit(1)
}

const secret = process.env.NUXT_JWT_SECRET || process.env.JWT_SECRET
if (!secret) {
  console.error('Missing NUXT_JWT_SECRET / JWT_SECRET in .env')
  process.exit(1)
}

;(async () => {
  await mongoose.connect(process.env.MONGODB_URI)
  const db = mongoose.connection.db

  const preReg = await db.collection('preregistrations').findOne({ email: EMAIL })
  if (!preReg) {
    console.error(`No preregistration found for ${EMAIL}`)
    await mongoose.disconnect()
    process.exit(1)
  }

  const jti = randomUUID()
  const token = jwt.sign(
    { preRegistrationId: preReg._id.toString(), jti, type: 'prereg-invite' },
    secret,
    { expiresIn: '48h' },
  )

  await db.collection('preregistrations').updateOne(
    { _id: preReg._id },
    { $set: { magicLinkJti: jti, magicLinkJtiUsed: false, status: 'invited' } },
  )

  const link = `${BASE_URL.replace(/\/$/, '')}/accept-invite#${token}`
  console.log('\nFresh invite link for', EMAIL, ':\n')
  console.log(link, '\n')

  await mongoose.disconnect()
})()
