import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:go_router/go_router.dart';
import 'package:onesignal_flutter/onesignal_flutter.dart';

// ─── Replace with your OneSignal App ID from onesignal.com ──────────────────
const _kOneSignalAppId = '524cb6d8-2640-4f85-bb24-c9c762233de7';
// ────────────────────────────────────────────────────────────────────────────

class NotificationService {
  NotificationService._();

  static GoRouter? _router;
  static bool _initialized = false;

  static void setRouter(GoRouter router) => _router = router;

  static bool get _supported =>
      !kIsWeb && (Platform.isIOS || Platform.isAndroid || Platform.isMacOS);

  static Future<void> init() async {
    if (!_supported || _initialized) return;
    _initialized = true;

    OneSignal.initialize(_kOneSignalAppId);
    await OneSignal.Notifications.requestPermission(true);

    // Show notification even when app is in foreground
    OneSignal.Notifications.addForegroundWillDisplayListener((event) {
      event.notification.display();
    });

    // Tap → navigate to job detail
    OneSignal.Notifications.addClickListener((event) {
      final data = event.notification.additionalData;
      if (data == null) return;
      final jobId = data['job_id'] as String?;
      final tenantType = data['tenant_type'] as String?;
      if (jobId == null || _router == null) return;
      if (tenantType == 'lab') {
        _router!.push('/lab/jobs/$jobId');
      } else {
        _router!.push('/clinic/jobs/$jobId');
      }
    });
  }

  /// Call after successful login. Links the OneSignal player to this user.
  static Future<void> loginUser(String userId, {bool isLab = false}) async {
    if (!_supported) return;
    try {
      await OneSignal.login(userId);
      OneSignal.User.addTagWithKey('tenant_type', isLab ? 'lab' : 'clinic');
    } catch (_) {}
  }

  /// Call on logout.
  static Future<void> logoutUser() async {
    if (!_supported) return;
    try {
      await OneSignal.logout();
    } catch (_) {}
  }
}
