import 'dart:io';

import 'package:dio/dio.dart';
import 'package:recording_tool/app/config/app_config.dart';
import 'package:recording_tool/app/router/app_navigator.dart';
import 'package:recording_tool/core/cache/app_storage.dart';
import 'package:recording_tool/core/cache/storage_keys.dart';
import 'package:recording_tool/core/utils/device_utils.dart';
import 'package:recording_tool/features/auth/pages/page_auth.dart';
import 'package:recording_tool/shared/widgets/app_toast.dart';

class HeaderInterceptor extends Interceptor {
  @override
  Future<void> onRequest(
    RequestOptions options,
    RequestInterceptorHandler handler,
  ) async {
    final token = AppStorage.getString(StorageKeys.authToken);
    if (token != null && token.isNotEmpty) {
      options.headers['Authorization'] = 'Bearer $token';
    }

    final packageInfo = AppConfig.packageInfo;
    final device = await DeviceUtils.deviceInfo();
    options.headers.addAll({
      'platform': Platform.operatingSystem,
      if (packageInfo != null) 'appVersion': packageInfo.version,
      'environment': AppConfig.current.environment.name,
      ...device,
    });

    handler.next(options);
  }

  @override
  Future<void> onError(
    DioException err,
    ErrorInterceptorHandler handler,
  ) async {
    if (err.response?.statusCode == 401) {
      await AppStorage.remove(StorageKeys.authToken);
      AppToast.show('口令已过期，请重新输入执裁口令');
      AppNavigator.pushAndRemoveUntil(AuthPageWidget());
    }
    handler.next(err);
  }
}
