require('dotenv').config();
const fs = require('fs');
const path = require('path');
const mysql = require('mysql2/promise');
const bcrypt = require('bcryptjs');

async function install() {
  console.log('🚀 Instalando HelpDesk ITSM v2.0...\n');

  const conn = await mysql.createConnection({
    host: process.env.DB_HOST || 'localhost',
    user: process.env.DB_USER || 'root',
    password: process.env.DB_PASSWORD || '',
    multipleStatements: true
  });

  const db = process.env.DB_NAME || 'sistema_soporte';
  await conn.query(`CREATE DATABASE IF NOT EXISTS \`${db}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`);
  await conn.query(`USE \`${db}\``);
  console.log(`✅ Base de datos "${db}" lista`);

  const schema = fs.readFileSync(path.join(__dirname, '..', 'database', 'schema.sql'), 'utf-8');
  await conn.query(schema);
  console.log('✅ Tablas y datos iniciales creados');

  // Hash passwords
  const adminPass = await bcrypt.hash('Laboratorio@2025*', 10);
  const agentPass = await bcrypt.hash('Agente2025*', 10);
  const clientPass = await bcrypt.hash('Cliente2025*', 10);

  // Update admin password (already inserted by schema)
  await conn.query('UPDATE users SET password=? WHERE email="admin@laboratorio.com"', [adminPass]);

  // Create agent and client
  await conn.query(`INSERT IGNORE INTO users (name,email,password,role,department) VALUES
    ('Agente Soporte', 'agente@laboratorio.com', ?, 'agent', 'Soporte TI'),
    ('Cliente Demo', 'cliente@laboratorio.com', ?, 'client', 'Operaciones')`, [agentPass, clientPass]);

  console.log('\n✅ Usuarios creados:');
  console.log('   👨‍💼 Admin:   admin@laboratorio.com / Laboratorio@2025*');
  console.log('   🛠️  Agente:  agente@laboratorio.com / Agente2025*');
  console.log('   👤 Cliente: cliente@laboratorio.com / Cliente2025*');

  // Ensure uploads dir
  const uploadsDir = path.join(__dirname, '..', 'public', 'uploads');
  if (!fs.existsSync(uploadsDir)) fs.mkdirSync(uploadsDir, { recursive: true });

  await conn.end();
  console.log('\n🎉 ¡Instalación completada!');
  console.log('   Ejecuta: npm start\n');
}

install().catch(err => {
  console.error('❌ Error:', err.message);
  process.exit(1);
});
