<?php

namespace App\Jobs;

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

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

    protected $campaign;

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

    /**
     * Execute the job.
     *
     * @throws Throwable
     */
    public function handle(): void
    {
        if ($this->campaign->isPaused()){
            return;
        }

        try {
            $this->campaign->run();
        }catch (Throwable $exception){
            $errorMsg = "Error scheduling campaign: ".$exception->getMessage()."\n".$exception->getTraceAsString();
            $this->campaign->failed($errorMsg);

            throw $exception;
        }
    }
}
