/**
 * Script standalone para testar a conexão Baileys e exibir o QR Code no terminal.
 * Não requer banco de dados nem DragonflyDB.
 * Uso: node qr-test.mjs
 */

import {
  makeWASocket,
  useMultiFileAuthState,
  DisconnectReason,
  fetchLatestBaileysVersion,
  makeCacheableSignalKeyStore,
} from '@whiskeysockets/baileys'
import { Boom } from '@hapi/boom'
import qrcode from 'qrcode-terminal'
import path from 'path'
import { fileURLToPath } from 'url'

const __dirname = path.dirname(fileURLToPath(import.meta.url))
const SESSION_DIR = path.join(__dirname, 'sessions', 'qr-test')

async function start() {
  const { state, saveCreds } = await useMultiFileAuthState(SESSION_DIR)
  const { version, isLatest } = await fetchLatestBaileysVersion()

  console.log(`\n📱 Baileys v${version} (latest: ${isLatest})`)
  console.log('🔄 Iniciando conexão...\n')

  const sock = makeWASocket({
    version,
    auth: state,
    printQRInTerminal: false, // controlamos manualmente
    qrTimeout: 60_000,
    browser: ['NewWhats', 'Chrome', '124.0.0'],
    syncFullHistory: false,
  })

  sock.ev.on('creds.update', saveCreds)

  sock.ev.on('connection.update', ({ connection, lastDisconnect, qr }) => {
    if (qr) {
      console.clear()
      console.log('📲 Escaneie o QR Code abaixo com o WhatsApp:\n')
      qrcode.generate(qr, { small: true })
      console.log('\n⏳ Aguardando escaneamento...')
    }

    if (connection === 'open') {
      const me = sock.user
      console.log('\n✅ Conectado com sucesso!')
      console.log(`   Número: ${me?.id}`)
      console.log(`   Nome:   ${me?.name}`)
      console.log('\n🎉 Sessão salva em:', SESSION_DIR)
      console.log('   Agora rode o servidor completo com: npm run dev\n')
    }

    if (connection === 'close') {
      const code = (lastDisconnect?.error)?.output?.statusCode
      const reason = DisconnectReason

      console.log(`\n❌ Conexão encerrada (código: ${code})`)

      const shouldReconnect =
        code !== reason.loggedOut &&
        code !== reason.forbidden

      if (shouldReconnect) {
        console.log('🔄 Reconectando...\n')
        setTimeout(start, 3000)
      } else {
        console.log('🚫 Sessão encerrada definitivamente.')
        process.exit(0)
      }
    }
  })
}

start().catch((err) => {
  console.error('Erro fatal:', err)
  process.exit(1)
})
