import 'package:shelf/shelf.dart';
import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart';
import 'package:dotenv/dotenv.dart';
import 'dart:convert';

class AuthMiddleware {
  final Future<Response> Function(Request, String) handler;
  
  AuthMiddleware(this.handler);
  
  Future<Response> call(Request request) async {
    final authorization = request.headers['authorization'];
    
    if (authorization == null || !authorization.startsWith('Bearer ')) {
      return Response(401, body: jsonEncode({'error': 'Authorization header missing or invalid'}), headers: {'Content-Type': 'application/json'});
    }
    
    final token = authorization.substring(7);
    
    try {
      final dotenv = DotEnv();
      final secret = dotenv['JWT_SECRET'] ?? '';
      final jwt = JWT.verify(token, SecretKey(secret));
      final payload = jwt.payload;
      final login = payload['login'] as String;
      
      return handler(request, login);
    } on JWTExpiredException {
      return Response(401, body: jsonEncode({'error': 'Token expired'}), headers: {'Content-Type': 'application/json'});
    } on JWTException {
      return Response(401, body: jsonEncode({'error': 'Invalid token'}), headers: {'Content-Type': 'application/json'});
    }
  }
}