import 'package:dio/dio.dart';

import 'demo_marianumconnect.dart';
import 'demo_mode.dart';

/// Answers every MarianumConnect request from fixtures while a demo session is
/// active, so the app makes no MC network calls. Installed first on the MC dio
/// so it resolves before the auth interceptor tries to attach a (non-existent)
/// bearer token.
class DemoMarianumConnectInterceptor extends Interceptor {
  static const _apiMarker = '/api/mobile/v1/';

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    if (!DemoMode.active) {
      handler.next(options);
      return;
    }
    handler.resolve(
      Response<dynamic>(
        requestOptions: options,
        statusCode: 200,
        data: DemoMarianumConnect.responseBody(
          _relativePath(options.uri),
          options.queryParameters,
        ),
      ),
    );
  }

  static String _relativePath(Uri uri) {
    final i = uri.path.indexOf(_apiMarker);
    return i >= 0 ? uri.path.substring(i + _apiMarker.length) : uri.path;
  }
}
