

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 {
      
      const authHeader = req.headers.authorization;
      if (!authHeader || !authHeader.startsWith("Bearer ")) {
        throw CustomError.unauthorized("Missing or invalid Authorization header");
      }

      const token = authHeader.substring(7); 

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

      
      const repository = new AuthRepositoryImpl();
      const user = await repository.findById(payload.id);
      if (!user) {
        throw CustomError.unauthorized("User not found");
      }

      
      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" });
    }
  }
}