<?php

namespace App\Jobs;

use App\Library\Traits\Trackable;
use App\Models\Campaigns;
use Illuminate\Bus\Batchable;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class LoadCampaign implements ShouldQueue
{
    use Trackable, Batchable, Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $campaign;

    public $failOnTimeout = false;
    public $timeout       = 120000;

    /**
     * Create a new job instance.
     */
    public function __construct(Campaigns $campaign)
    {
        $this->campaign = $campaign;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        if ($this->batch()->cancelled()) {
            return;
        }

        $this->campaign->processing();
        $server = $this->campaign->getSendingServers();

        $this->campaign->prepare(function ($campaign, $contact) use ($server) {
            $this->batch()->add(new SendMessage($campaign, $contact, $server));
        });
    }
}
