import { Request, Response, NextFunction } from 'express';
import { verifyAccessToken } from '../utils/jwt';
import { findUserById } from '../repositories/users.repository';
import { sendError } from '../utils/apiResponse';

export const authenticate = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const authHeader = req.headers.authorization;
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return sendError(res, 401, 'Non authentifié');
    }

    const token = authHeader.split(' ')[1];
    
    try {
      const payload = verifyAccessToken(token);
      
      const user = await findUserById(payload.sub);
      
      if (!user) {
        return sendError(res, 401, 'Utilisateur introuvable');
      }
      
      if (user.status !== 'ACTIVE') {
        return sendError(res, 403, 'Compte inactif ou banni');
      }

      req.user = {
        id: user.id,
        email: user.email,
        role: payload.role, // On pourrait utiliser user.role_id, mais on a mis le nom du rôle dans le token.
        status: user.status
      };
      
      next();
    } catch (err) {
      return sendError(res, 401, 'Token invalide ou expiré');
    }
  } catch (error) {
    next(error);
  }
};

export const optionalAuthenticate = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const authHeader = req.headers.authorization;
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return next();
    }

    const token = authHeader.split(' ')[1];
    
    try {
      const payload = verifyAccessToken(token);
      const user = await findUserById(payload.sub);
      
      if (user && user.status === 'ACTIVE') {
        req.user = {
          id: user.id,
          email: user.email,
          role: payload.role,
          status: user.status
        };
      }
    } catch (err) {
      // Ignorer l'erreur pour optionalAuthenticate
    }
    
    next();
  } catch (error) {
    next(error);
  }
};
