/**
 * auth.middleware.ts
 * Middleware para validar el JWT.
 * - Lee el token del header Authorization: Bearer TOKEN
 * - Valida el token
 * - Busca el usuario en base de datos
 * - Agrega el usuario a req.user
 */

import { Request, Response, NextFunction } from "express";
import { JwtAdapter, JwtPayload } from "../../config/jwt.js";
import { AuthRepositoryImpl } from "../../data/repositories/auth.repository.impl.js";
import { CustomError } from "../../domain/errors/custom.error.js";

export interface AuthRequest extends Request {
  user?: JwtPayload;
}

export class AuthMiddleware {
  static async validate(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      // Obtener el token del header
      const authHeader = req.headers.authorization;
      if (!authHeader || !authHeader.startsWith("Bearer ")) {
        throw CustomError.unauthorized("Missing or invalid Authorization header");
      }

      const token = authHeader.substring(7); // Remover "Bearer "

      // Validar el token
      const payload = JwtAdapter.validate(token);
      if (!payload) {
        throw CustomError.unauthorized("Invalid token");
      }

      // Verificar que el usuario existe en BD
      const repository = new AuthRepositoryImpl();
      const user = await repository.findById(payload.id);
      if (!user) {
        throw CustomError.unauthorized("User not found");
      }

      // Agregar el usuario al request
      req.user = payload;

      next();
    } catch (error) {
      if (error instanceof CustomError) {
        return res.status(error.statusCode).json({ error: error.message });
      }
      res.status(500).json({ error: "Internal server error" });
    }
  }
}