package chat.vojo.app;

import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

/**
 * Dismisses the incoming-call notification when its RTC lifetime expires.
 *
 * Scheduled by {@link VojoFirebaseMessagingService} via AlarmManager at
 * sender_ts + lifetime. The extras carry tag/id so we can target the exact
 * notification even if multiple ring pushes overlap (rare but possible across
 * rapid re-dials).
 *
 * Also invoked directly (same intent shape) when the app receives a decline /
 * other-device-answer via the live Matrix sync and wants the system notification
 * cleared — see Capacitor removeDeliveredNotifications in the JS layer.
 */
public class CallCancelReceiver extends BroadcastReceiver {

    public static final String ACTION_CANCEL_CALL = "chat.vojo.app.CANCEL_CALL";
    public static final String EXTRA_NOTIF_TAG = "notif_tag";
    public static final String EXTRA_NOTIF_ID = "notif_id";
    // Carried so the receiver can tombstone and drop the matching registry
    // entry — otherwise a same-eventId re-delivery after expiry would seed the
    // registry again and render a stale ring on next backgrounding.
    public static final String EXTRA_NOTIF_EVENT_ID = "notif_event_id";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent == null || !ACTION_CANCEL_CALL.equals(intent.getAction())) return;
        String tag = intent.getStringExtra(EXTRA_NOTIF_TAG);
        int id = intent.getIntExtra(EXTRA_NOTIF_ID, -1);
        String notifEventId = intent.getStringExtra(EXTRA_NOTIF_EVENT_ID);
        if (tag == null || id == -1) return;
        NotificationManager nm =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (nm != null) nm.cancel(tag, id);
        if (notifEventId != null) {
            VojoFirebaseMessagingService.removeIncomingRing(context, notifEventId);
        }
    }
}
