<?php namespace App\Jobs\Shopify;

use App\Models\Customer;
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 SyncCustomer implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

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

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

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