<?php

namespace App\Jobs;

use App\Library\Tool;
use App\Library\Traits\Trackable;
use App\Models\Automation;
use App\Models\SendingServer;
use App\Models\User;
use Illuminate\Bus\Batch;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Bus;
use Throwable;

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

    protected $automation;
    protected $contacts;

    /**
     * Create a new job instance.
     */
    public function __construct(Automation $automation, $contacts)
    {
        $this->automation = $automation;
        $this->contacts   = $contacts;
    }

    /**
     * Execute the job.
     *
     * @throws Throwable
     */
    public function handle()
    {
        $server = SendingServer::where('status', true)->find($this->automation->sending_server_id);
        if ( ! $server) {
            return;
        }

        $batch_list = [];
        $user       = User::find($this->automation->user_id);

        $user->customer->cleanupQuotaTracker();
        Tool::resetMaxExecutionTime();

        $this->contacts->chunk(100)
                       ->each(function ($contact) use (&$batch_list, $server, $user) {
                           $batch_list[] = new SendAutomationMessage($this->automation, $contact, $server, $user);
                       });

        Bus::batch($batch_list)
           ->allowFailures(false)
           ->dispatch();
    }
}
