<?php

namespace App\Jobs;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Minishlink\WebPush\Subscription;
use Minishlink\WebPush\WebPush;

class StorePushNotification implements ShouldQueue
{
    use Queueable;

    /**
     * Create a new job instance.
     */
    public function __construct(
        protected $notificationQuery,
        protected array $payload
    ) {
        //
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $auth = [
            'VAPID' => [
                'subject' => config('app.url'),
                'publicKey' => config('services.vapid.public_key'),
                'privateKey' => config('services.vapid.private_key'),
            ],

        ];

        $webPush = new WebPush($auth);

        $payload = json_encode($this->payload);

        foreach ($this->notificationQuery as $notification) {
            $webPush->sendOneNotification(
                Subscription::create(json_decode($notification->subscriptions, true)),
                $payload,
                ['TTL' => 5000],
            );
        }
    }
}
