import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart' as permission;
import '../utils/platform_helper.dart';
import '../l10n/app_localizations.dart';
import '../navigator_key.dart';

class SMSService {
  static const platform = MethodChannel('com.submanager/sms');

  static Future<bool> requestSMSPermission() async {
    // 웹이나 iOS에서는 SMS 권한 불필요
    if (kIsWeb || PlatformHelper.isIOS) return true;

    // Android에서만 권한 요청
    if (PlatformHelper.isAndroid) {
      final status = await permission.Permission.sms.request();
      return status.isGranted;
    }

    return false;
  }

  static Future<bool> hasSMSPermission() async {
    // 웹이나 iOS에서는 항상 true 반환 (권한 불필요)
    if (kIsWeb || PlatformHelper.isIOS) return true;

    // Android에서만 실제 권한 확인
    if (PlatformHelper.isAndroid) {
      final status = await permission.Permission.sms.status;
      return status.isGranted;
    }

    return false;
  }

  static Future<List<Map<String, dynamic>>> scanSubscriptions() async {
    if (kIsWeb) return [];

    try {
      if (!await hasSMSPermission()) {
        final loc = _loc();
        throw Exception(
            loc?.smsPermissionRequired ?? 'SMS permission required.');
      }

      final List<dynamic> result =
          await platform.invokeMethod('scanSubscriptions');
      return result.map((item) => item as Map<String, dynamic>).toList();
    } on PlatformException catch (e) {
      final loc = _loc();
      throw Exception(loc?.smsScanErrorWithMessage(e.message ?? '') ??
          'Error occurred during SMS scan: ${e.message}');
    }
  }

  static AppLocalizations? _loc() {
    final ctx = navigatorKey.currentContext;
    if (ctx == null) return null;
    return AppLocalizations.of(ctx);
  }
}
