import '../local/models/app_settings.dart';
import 'notification_inbox_service.dart';

/// Phase-4 bridge for future FCM/APNs wiring.
///
/// This app currently ships without Firebase/APNs SDK setup in source control.
/// Once push SDK is configured, route incoming payloads to [ingestPayload].
class RemotePushService {
  RemotePushService._();
  static final RemotePushService instance = RemotePushService._();

  final NotificationInboxService _inbox = NotificationInboxService.instance;

  Future<void> init() async {
    // Reserved for SDK wiring (FCM/APNs token registration, topic subscription).
  }

  Future<void> ingestPayload(
    Map<String, dynamic> payload, {
    AppSettings? settings,
  }) async {
    if (settings != null && !settings.inboxEnabled) return;

    final id = (payload['id'] ?? payload['messageId'] ?? '').toString().trim();
    final title = (payload['title'] ?? '').toString().trim();
    final body = (payload['body'] ?? '').toString().trim();
    if (id.isEmpty || title.isEmpty || body.isEmpty) return;

    final type = (payload['type'] ?? 'content').toString().trim();
    final deeplink = (payload['deeplink'] ?? '').toString().trim();
    final expiresAt =
        DateTime.tryParse((payload['expiresAt'] ?? '').toString().trim());
    final isPinned = payload['isPinned'] == true;

    await _inbox.addItem(
      title: title,
      body: body,
      type: type.isEmpty ? 'content' : type,
      source: 'remote',
      deeplink: deeplink.isEmpty ? null : deeplink,
      dedupeKey: 'remote.push.$id',
      expiresAt: expiresAt,
      isPinned: isPinned,
      meta: <String, dynamic>{'remoteId': id},
    );
  }
}
