<?php

namespace App\Jobs;

use App\Services\RevocationService;
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 ProcessAccessRevocation implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $accessDetailIds;
    public $revokedBy;
    public $notes;
    public $tries = 2;
    public $timeout = 120;

    public function __construct(array $accessDetailIds, int $revokedBy, ?string $notes = null)
    {
        $this->accessDetailIds = $accessDetailIds;
        $this->revokedBy = $revokedBy;
        $this->notes = $notes;
    }

    public function handle(RevocationService $revocationService): void
    {
        try {
            Log::info('Starting bulk revocation job', [
                'count' => count($this->accessDetailIds),
                'revoked_by' => $this->revokedBy
            ]);

            $results = $revocationService->bulkRevoke(
                $this->accessDetailIds,
                $this->revokedBy,
                $this->notes
            );

            Log::info('Bulk revocation job completed', [
                'success' => count($results['success']),
                'failed' => count($results['failed'])
            ]);

            // Notify admin about results
            if (count($results['failed']) > 0) {
                Log::warning('Some revocations failed', ['failed' => $results['failed']]);
            }

        } catch (\Exception $e) {
            Log::error('Bulk revocation job failed: ' . $e->getMessage(), [
                'error' => $e->getMessage()
            ]);
            
            $this->fail($e);
        }
    }

    public function failed(\Throwable $exception): void
    {
        Log::error('Bulk revocation job permanently failed', [
            'error' => $exception->getMessage(),
            'access_ids' => $this->accessDetailIds
        ]);
    }
}