const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const config = require('./config');

// Hash du mot de passe au démarrage
let passwordHash = null;

async function initAuth() {
  passwordHash = await bcrypt.hash(config.auth.password, 10);
}

async function authenticate(username, password) {
  if (username !== config.auth.username) {
    return null;
  }
  // Comparer directement car on stocke le mot de passe en clair dans la config
  if (password !== config.auth.password) {
    return null;
  }
  const token = jwt.sign(
    { username, role: 'admin' },
    config.jwtSecret,
    { expiresIn: config.jwtExpiry }
  );
  return token;
}

function verifyToken(token) {
  try {
    return jwt.verify(token, config.jwtSecret);
  } catch (err) {
    return null;
  }
}

function authMiddleware(req, res, next) {
  // Check Authorization header
  let token = null;
  const authHeader = req.headers.authorization;
  if (authHeader && authHeader.startsWith('Bearer ')) {
    token = authHeader.substring(7);
  }
  // Check cookie
  if (!token && req.cookies) {
    token = req.cookies.dashboard_token;
  }

  if (!token) {
    return res.status(401).json({ error: 'Non authentifié' });
  }

  const decoded = verifyToken(token);
  if (!decoded) {
    return res.status(401).json({ error: 'Token invalide ou expiré' });
  }

  req.user = decoded;
  next();
}

module.exports = { initAuth, authenticate, verifyToken, authMiddleware };
