<?php

namespace App\Listeners;

use App\Events\GRNPosted;
use App\Services\InventoryService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;

class ProcessGRNPosted implements ShouldQueue
{
    use InteractsWithQueue;

    protected $inventoryService;

    /**
     * Create the event listener.
     */
    public function __construct(InventoryService $inventoryService)
    {
        $this->inventoryService = $inventoryService;
    }

    /**
     * Handle the event.
     */
    public function handle(GRNPosted $event): void
    {
        try {
            Log::info("Processing GRN posted event for GRN: {$event->grn->grn_number}");

            $this->inventoryService->postGRN($event->grn->id);

            Log::info("Successfully processed GRN posted event for GRN: {$event->grn->grn_number}");
        } catch (\Exception $e) {
            Log::error("Failed to process GRN posted event for GRN {$event->grn->grn_number}: " . $e->getMessage());

            // Re-throw the exception to mark the job as failed
            throw $e;
        }
    }

    /**
     * Handle a job failure.
     */
    public function failed(GRNPosted $event, \Throwable $exception): void
    {
        Log::error("GRN posted event processing failed for GRN {$event->grn->grn_number}: " . $exception->getMessage());
    }
}
