<?php

namespace App\Jobs;

use App\Models\Delivery;
use App\Services\PushNotificationService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class SendCourierPushReminder implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct(
        public int $deliveryId,
        public int $attempt
    ) {
        $this->onQueue('default');
    }

    public function handle(PushNotificationService $push): void
    {
        $delivery = Delivery::query()
            ->with(['courier.users'])
            ->find($this->deliveryId);

        if (!$delivery) {
            return;
        }

        // Stop reminders once it is no longer awaiting acceptance.
        if ($delivery->status !== 'pending' || !$delivery->courier_id) {
            return;
        }

        $courier = $delivery->courier;
        if (!$courier || !$courier->is_active || !$courier->is_online) {
            return;
        }

        $assignedAt = $delivery->assigned_at ?? $delivery->updated_at;
        if (!$assignedAt) {
            return;
        }

        // Only remind within the 20s assignment window.
        if (now()->diffInSeconds($assignedAt) >= 20) {
            return;
        }

        // Ensure we don't send the same (or older) reminder more than once.
        if ((int) $delivery->push_attempt >= (int) $this->attempt) {
            return;
        }

        $delivery->forceFill([
            'push_attempt' => (int) $this->attempt,
            'push_last_sent_at' => now(),
        ])->save();

        $payload = [
            'title' => 'Nuevo pedido',
            'body' => 'Recordatorio: tienes un pedido pendiente por aceptar.',
            'url' => url('/courier'),
            // Use a per-delivery tag so repeated pushes "renotify" the same notification.
            'tag' => 'delivery-' . $delivery->id,
            'delivery_id' => $delivery->id,
        ];

        foreach ($courier->users as $user) {
            $push->sendToUser($user, $payload);
        }
    }
}

