import 'package:dio/dio.dart';
import '../../utils/token_storage.dart';
import '../api_client.dart';

class AuthInterceptor extends Interceptor {
  @override
  void onRequest(
      RequestOptions options, RequestInterceptorHandler handler) async {
    final token = await TokenStorage.getAccessToken();

    if (token != null) {
      options.headers["Authorization"] = "Bearer $token";
    }

    handler.next(options);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) async {
    if (err.response?.statusCode == 401) {
      final refreshToken = await TokenStorage.getRefreshToken();

      if (refreshToken != null) {
        try {
          final response = await ApiClient.dio.post(
            "/auth/refresh.php",
            data: {"refresh_token": refreshToken},
          );

          final newAccessToken = response.data["access_token"];

          await TokenStorage.saveTokens(
              newAccessToken, refreshToken);

          err.requestOptions.headers["Authorization"] =
              "Bearer $newAccessToken";

          final cloneReq = await ApiClient.dio.fetch(err.requestOptions);
          return handler.resolve(cloneReq);
        } catch (_) {
          await TokenStorage.clear();
        }
      }
    }

    handler.next(err);
  }
}