import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:uni_links/uni_links.dart';
import 'package:mypoint_flutter_app/directional/directional_screen.dart';
import 'package:mypoint_flutter_app/extensions/crypto.dart' as mycrypto;

class DeepLinkService {
  DeepLinkService._internal();
  static final DeepLinkService _instance = DeepLinkService._internal();
  factory DeepLinkService() => _instance;

  StreamSubscription? _linkSub;
  bool _initialized = false;

  Future<void> initialize() async {
    if (_initialized) return;
    _initialized = true;
    if (kDebugMode) print('🔗 Initializing DeepLinkService...');

    await _handleInitialLink();
    _listenLinkStream();
  }

  Future<void> dispose() async {
    await _linkSub?.cancel();
    _linkSub = null;
    _initialized = false;
  }

  Future<void> _handleInitialLink() async {
    try {
      final initial = await getInitialLink();
      if (initial == null) return;
      _routeFromUriString(initial);
    } catch (_) {}
  }

  void _listenLinkStream() {
    try {
      _linkSub = linkStream.listen((uri) {
        if (uri == null) return;
        _routeFromUriString(uri.toString());
      }, onError: (_) {});
    } catch (_) {}
  }

  // Firebase Dynamic Links removed due to version constraints.
  void _routeFromUriString(String uriStr) {
    if (kDebugMode) print('🔗 Deep link received: $uriStr');
    final uri = Uri.tryParse(uriStr);
    if (uri == null) return;

    final type = uri.queryParameters[Defines.actionType] ?? uri.queryParameters['action_type'];
    final param = uri.queryParameters[Defines.actionParams] ?? uri.queryParameters['action_param'];

    // Optional: decrypt phone from `key` if present (compat with iOS scheme handler)
    final cipherHex = uri.queryParameters['key'];
    if (cipherHex != null && cipherHex.isNotEmpty) {
      // Try multiple known secrets (match iOS CommonAPI.schemeCryptKey variants)
      const candidates = <String>[
        'mypointdeeplinkk',
        'PVt3FWQibsB7xaLx',
      ];
      for (final secret in candidates) {
        final phone = mycrypto.Crypto(cipherHex: cipherHex, secretKey: secret).decryption();
        if (phone != null && phone.isNotEmpty) {
          if (kDebugMode) print('🔐 Decrypted phone from key: $phone');
          break; // Use if you need to attach to userInfo later
        }
      }
    }

    final screen = DirectionalScreen.build(clickActionType: type, clickActionParam: param);
    screen?.begin();
  }
}


