import 'dart:convert';
import 'package:crypto/crypto.dart';
import 'package:dio/dio.dart';
import '../storage/secure_storage.dart';

class HmacInterceptor extends Interceptor {
  final SecureStorage secureStorage;

  HmacInterceptor(this.secureStorage);

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
    final token = await secureStorage.getToken();
    final deviceSecret = await secureStorage.getDeviceSecret();

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

    // Only sign if we have a device secret (after login)
    if (deviceSecret != null) {
      final timestamp = DateTime.now().millisecondsSinceEpoch.toString();
      
      // Create signature payload
      String payload = '${options.method}:${options.path}:$timestamp';
      
      // Include body in signature if present
      if (options.data != null && options.data is Map) {
        payload += ':${jsonEncode(options.data)}';
      }

      // Generate HMAC-SHA256
      final key = utf8.encode(deviceSecret);
      final bytes = utf8.encode(payload);
      final hmac = Hmac(sha256, key);
      final digest = hmac.convert(bytes);

      // Attach headers
      options.headers['X-Timestamp'] = timestamp;
      options.headers['X-Signature'] = digest.toString();
    }

    super.onRequest(options, handler);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    if (err.response?.statusCode == 401) {
      // Handle Token Expiry / Unauthorized
      // TODO: Trigger logout or token refresh
    }
    super.onError(err, handler);
  }
}
