<?php

namespace App\Jobs;

use App\Services\IdentityVerificationService;
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;

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

    /**
     * The number of times the job may be attempted.
     *
     * @var int
     */
    public $tries = 3;

    /**
     * The number of seconds to wait before retrying the job.
     *
     * @var int
     */
    public $backoff = 60;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     *
     * @param IdentityVerificationService $service
     * @return void
     */
    public function handle(IdentityVerificationService $service)
    {
        Log::info('CancelExpiredProvisionalOrders: Starting job');

        try {
            $result = $service->cancelExpiredProvisionalOrders();

            Log::info('CancelExpiredProvisionalOrders: Completed', [
                'cancelled_count' => $result['cancelled_count'],
                'errors_count' => count($result['errors']),
            ]);

            if (!empty($result['errors'])) {
                Log::warning('CancelExpiredProvisionalOrders: Some orders failed to cancel', [
                    'errors' => $result['errors'],
                ]);
            }
        } catch (\Exception $e) {
            Log::error('CancelExpiredProvisionalOrders: Job failed', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            throw $e;
        }
    }

    /**
     * Handle a job failure.
     *
     * @param \Throwable $exception
     * @return void
     */
    public function failed(\Throwable $exception)
    {
        Log::error('CancelExpiredProvisionalOrders: Job permanently failed', [
            'error' => $exception->getMessage(),
        ]);
    }
}
