/**
 * SQLite local — controle de agentes (auth + config)
 * Login unificado: todos os usuarios na tabela agentes com coluna 'role'
 */
const Database = require('better-sqlite3');
const path = require('path');

const DB_PATH = path.join(__dirname, '..', 'data', 'agentes.db');
const db = new Database(DB_PATH);

// WAL mode for better concurrency
db.pragma('journal_mode = WAL');

// Create tables
db.exec(`
  CREATE TABLE IF NOT EXISTS agentes (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    email TEXT UNIQUE NOT NULL,
    senha_hash TEXT NOT NULL,
    agente_id INTEGER NOT NULL,
    nome TEXT NOT NULL,
    role TEXT DEFAULT 'agente',
    ativo INTEGER DEFAULT 1,
    created_at TEXT DEFAULT (datetime('now'))
  )
`);

// Add role column if it doesn't exist (migration for existing databases)
try {
  db.exec(`ALTER TABLE agentes ADD COLUMN role TEXT DEFAULT 'agente'`);
} catch (e) {
  // Column already exists, ignore
}

// Add permissions column (migration)
try {
  db.exec(`ALTER TABLE agentes ADD COLUMN permissions TEXT DEFAULT '[]'`);
} catch (e) {
  // Column already exists, ignore
}

// Migrate existing users with empty permissions — set defaults based on role
const { DEFAULT_PERMISSIONS } = require('./panels');
const usersNeedingPerms = db.prepare("SELECT id, role FROM agentes WHERE permissions = '[]' OR permissions IS NULL").all();
for (const u of usersNeedingPerms) {
  const defaults = DEFAULT_PERMISSIONS[u.role] || DEFAULT_PERMISSIONS.agente;
  db.prepare('UPDATE agentes SET permissions = ? WHERE id = ?').run(JSON.stringify(defaults), u.id);
}

// Legacy table - keep for reference but no longer used
db.exec(`
  CREATE TABLE IF NOT EXISTS admins (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    email TEXT UNIQUE NOT NULL,
    senha_hash TEXT NOT NULL,
    nome TEXT NOT NULL,
    created_at TEXT DEFAULT (datetime('now'))
  )
`);

// Migrate existing admins to agentes table with role='admin'
const admins = db.prepare('SELECT * FROM admins').all();
for (const admin of admins) {
  try {
    db.prepare(`
      INSERT OR IGNORE INTO agentes (email, senha_hash, nome, role, agente_id, ativo)
      VALUES (?, ?, ?, 'admin', 0, 1)
    `).run(admin.email, admin.senha_hash, admin.nome);
  } catch (e) {
    // Email already exists in agentes, skip
  }
}

// Alerts table
db.exec(`
  CREATE TABLE IF NOT EXISTS alerts (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    severity TEXT NOT NULL,
    message TEXT NOT NULL,
    data TEXT,
    acknowledged INTEGER DEFAULT 0,
    created_at TEXT DEFAULT (datetime('now'))
  )
`);

module.exports = db;
