#!/usr/bin/env node
/**
 * migrate-sqlite-to-pg.js
 * Migra os dados existentes do database.sqlite para o PostgreSQL.
 * Execute UMA ÚNICA VEZ: node database/migrate-sqlite-to-pg.js
 */
'use strict'

const path = require('path')
const fs   = require('fs')
const { Pool } = require('pg')

// ── Configuração PostgreSQL ──────────────────────────────────────
const pool = new Pool({
  host:     process.env.PG_HOST     || 'localhost',
  port:     parseInt(process.env.PG_PORT || '5432'),
  database: process.env.PG_DATABASE || 'alemao',
  user:     process.env.PG_USER     || 'newwhats',
  password: process.env.PG_PASSWORD || 'newwhats123',
})

// ── Load SQLite via sql.js ───────────────────────────────────────
const DB_PATH = path.resolve(__dirname, '..', 'database.sqlite')

async function migrate() {
  console.log('\n🔄 Iniciando migração SQLite → PostgreSQL...\n')

  if (!fs.existsSync(DB_PATH)) {
    console.error('❌ database.sqlite não encontrado em:', DB_PATH)
    process.exit(1)
  }

  const initSqlJs = require('sql.js')
  const SQL       = await initSqlJs()
  const fileBuffer = fs.readFileSync(DB_PATH)
  const db        = new SQL.Database(fileBuffer)

  const client = await pool.connect()

  try {
    await client.query('BEGIN')

    // ── Admins ──────────────────────────────────────────────────
    console.log('📋 Migrando admins...')
    const admins = db.exec('SELECT * FROM admins')[0]
    if (admins) {
      for (const row of admins.values) {
        const [id, username, password_hash, nome, email, telefone] = row
        await client.query(
          `INSERT INTO admins (id, username, password_hash, nome, email, telefone)
           VALUES ($1,$2,$3,$4,$5,$6) ON CONFLICT (username) DO NOTHING`,
          [id, username, password_hash, nome || null, email || null, telefone || null]
        )
      }
      // Sincronizar sequence
      await client.query(`SELECT setval('admins_id_seq', (SELECT MAX(id) FROM admins))`)
      console.log(`   ✅ ${admins.values.length} admins migrados`)
    }

    // ── Users ───────────────────────────────────────────────────
    console.log('📋 Migrando users...')
    const users = db.exec('SELECT * FROM users')[0]
    if (users) {
      let count = 0
      for (const row of users.values) {
        // Colunas reais: id, nome, cpf, telefone, ip, timestamp, source, email
        const [id, nome, cpf, telefone, ip, timestamp, source, email] = row
        await client.query(
          `INSERT INTO users (id, nome, email, cpf, telefone, ip, source, timestamp)
           VALUES ($1,$2,$3,$4,$5,$6,$7,$8) ON CONFLICT DO NOTHING`,
          [id, nome, email || null, cpf || null, telefone || null, ip || null, source || 'hotspot', timestamp || new Date()]
        )
        count++
      }
      await client.query(`SELECT setval('users_id_seq', (SELECT MAX(id) FROM users))`)
      console.log(`   ✅ ${count} users migrados`)
    }

    // ── Raffles ─────────────────────────────────────────────────
    console.log('📋 Migrando raffles...')
    const raffles = db.exec('SELECT * FROM raffles')[0]
    if (raffles) {
      for (const row of raffles.values) {
        const [id, titulo, descricao, preco_numero, total_numeros, ativo, data_criacao] = row
        await client.query(
          `INSERT INTO raffles (id, titulo, descricao, preco_numero, total_numeros, ativo, data_criacao)
           VALUES ($1,$2,$3,$4,$5,$6,$7) ON CONFLICT DO NOTHING`,
          [id, titulo, descricao || null, preco_numero || 5.0, total_numeros || 500, ativo, data_criacao || new Date()]
        )
      }
      await client.query(`SELECT setval('raffles_id_seq', (SELECT MAX(id) FROM raffles))`)
      console.log(`   ✅ ${raffles.values.length} sorteios migrados`)
    }

    // ── Tickets ─────────────────────────────────────────────────
    console.log('📋 Migrando tickets...')
    const tickets = db.exec('SELECT * FROM tickets')[0]
    if (tickets) {
      for (const row of tickets.values) {
        const [id, raffle_id, numero, usuario_nome, usuario_telefone, usuario_cpf, data_compra] = row
        await client.query(
          `INSERT INTO tickets (id, raffle_id, numero, usuario_nome, usuario_telefone, usuario_cpf, data_compra)
           VALUES ($1,$2,$3,$4,$5,$6,$7) ON CONFLICT DO NOTHING`,
          [id, raffle_id, numero, usuario_nome, usuario_telefone || null, usuario_cpf || null, data_compra || new Date()]
        )
      }
      await client.query(`SELECT setval('tickets_id_seq', (SELECT MAX(id) FROM tickets))`)
      console.log(`   ✅ ${tickets.values.length} tickets migrados`)
    }

    // ── Promotions ──────────────────────────────────────────────
    console.log('📋 Migrando promotions...')
    const promos = db.exec('SELECT * FROM promotions')[0]
    if (promos) {
      for (const row of promos.values) {
        const [id, nome, descricao, preco_original, preco_promocional, imagem, ativo, data_criacao] = row
        await client.query(
          `INSERT INTO promotions (id, nome, descricao, preco_original, preco_promocional, imagem, ativo, data_criacao)
           VALUES ($1,$2,$3,$4,$5,$6,$7,$8) ON CONFLICT DO NOTHING`,
          [id, nome, descricao || null, preco_original || null, preco_promocional, imagem || '', ativo, data_criacao || new Date()]
        )
      }
      await client.query(`SELECT setval('promotions_id_seq', (SELECT MAX(id) FROM promotions))`)
      console.log(`   ✅ ${promos.values.length} promoções migradas`)
    }

    await client.query('COMMIT')
    console.log('\n🎉 Migração concluída com sucesso!\n')

  } catch (err) {
    await client.query('ROLLBACK')
    console.error('\n❌ Migração falhou — rollback executado:', err.message)
    process.exit(1)
  } finally {
    client.release()
    await pool.end()
  }
}

migrate()
