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';

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()) {
        throw Exception('SMS 권한이 없습니다.');
      }

      final List<dynamic> result =
          await platform.invokeMethod('scanSubscriptions');
      return result.map((item) => item as Map<String, dynamic>).toList();
    } on PlatformException catch (e) {
      throw Exception('SMS 스캔 중 오류 발생: ${e.message}');
    }
  }
}
