import 'package:dio/dio.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import '../services/device_header_service.dart';

const _kJwtKey = 'jwt_token';
const _storage = FlutterSecureStorage();

Future<void> saveJwt(String token) =>
    _storage.write(key: _kJwtKey, value: token);
Future<void> clearJwt() => _storage.delete(key: _kJwtKey);
Future<String?> loadJwt() => _storage.read(key: _kJwtKey);

class AuthInterceptor extends Interceptor {
  @override
  Future<void> onRequest(
    RequestOptions options,
    RequestInterceptorHandler handler,
  ) async {
    await DeviceHeaderService.to.ensureInitialized();
    options.headers.addAll(DeviceHeaderService.to.commonHeaders());
    options.headers.addAll(DeviceHeaderService.to.platformIdentityHeaders());
    final jwt = await loadJwt();
    if (jwt != null && jwt.isNotEmpty) {
      options.headers['Authorization'] = 'Bearer $jwt';
    }
    handler.next(options);
  }
}
