/**
 * Admin Authentication - login/logout with bcrypt + express-session
 */
const bcrypt = require('bcrypt');
const db = require('./db-local');

const SALT_ROUNDS = 10;

async function createAdmin(email, senha, nome) {
  const hash = await bcrypt.hash(senha, SALT_ROUNDS);
  return db.prepare(
    'INSERT INTO admins (email, senha_hash, nome) VALUES (?, ?, ?)'
  ).run(email, hash, nome);
}

async function authenticateAdmin(email, senha) {
  const row = db.prepare(
    'SELECT * FROM admins WHERE email = ?'
  ).get(email);
  if (!row) return null;
  const match = await bcrypt.compare(senha, row.senha_hash);
  return match ? row : null;
}

function requireAdmin(req, res, next) {
  if (req.session && req.session.admin) return next();
  res.redirect('/admin/login');
}

async function updateAdminPassword(id, novaSenha) {
  const hash = await bcrypt.hash(novaSenha, SALT_ROUNDS);
  return db.prepare(
    'UPDATE admins SET senha_hash = ? WHERE id = ?'
  ).run(hash, id);
}

module.exports = { createAdmin, authenticateAdmin, requireAdmin, updateAdminPassword };
