<?php namespace App\Jobs\Shopify;

use App\Models\Company;
use App\Services\Shopify\CustomersService;
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\Log;
use RuntimeException;

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

    /**
     * Id for the product to sync
     *
     * @var int
     */
    protected $companyId;
    public $backoff = [3, 30, 100];

    /**
     * Create a new job instance.
     *
     * @param stdClass $data
     *
     * @return void
     */
    public function __construct(int $companyId)
    {
        $this->companyId = $companyId;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle(CustomersService $service)
    {
        Log::info('Sync company with shopify - ' . $this->companyId);
        $company = Company::find($this->companyId);
        if (!$company) {
            Log::warning('Sync company with shopify - company not found');
            return;
        }
        if (!$company->to_sync) {
            Log::warning('Sync company with shopify - company not marked to sync');
            return;
        }
        if (!$service->syncCompany($company)) {
            Log::warning('Sync company with shopify - Error syncing company');
        }
        Log::info('Sync company with shopify - success');
    }
}
