import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:url_launcher/url_launcher.dart';

abstract class ContactLauncher {
  const ContactLauncher();

  Future<bool> call(String phoneNumber);

  Future<bool> sms(String phoneNumber);
}

class UrlLauncherContactLauncher implements ContactLauncher {
  const UrlLauncherContactLauncher();

  @override
  Future<bool> call(String phoneNumber) async {
    final uri = buildCallUri(phoneNumber);
    if (uri == null) {
      return false;
    }
    return launchUrl(uri);
  }

  @override
  Future<bool> sms(String phoneNumber) async {
    final uri = buildSmsUri(phoneNumber);
    if (uri == null) {
      return false;
    }
    return launchUrl(uri);
  }
}

Uri? buildCallUri(String phoneNumber) {
  final normalized = _normalizePhoneNumber(phoneNumber);
  if (normalized == null) {
    return null;
  }
  return Uri(scheme: 'tel', path: normalized);
}

Uri? buildSmsUri(String phoneNumber) {
  final normalized = _normalizePhoneNumber(phoneNumber);
  if (normalized == null) {
    return null;
  }
  return Uri(scheme: 'sms', path: normalized);
}

String? _normalizePhoneNumber(String value) {
  final normalized = value.replaceAll(RegExp(r'[^0-9+]'), '');
  if (normalized.isEmpty) {
    return null;
  }
  return normalized;
}

final contactLauncherProvider = Provider<ContactLauncher>((ref) {
  return const UrlLauncherContactLauncher();
});
