<?php

namespace App\Domain\Inventory\Listeners;

use App\Domain\Inventory\Events\ProductLowStock;
use App\Domain\Inventory\Models\InventoryLevel;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;

class CheckLowStockThreshold implements ShouldQueue
{
    public function handle($event): void
    {
        try {
            // This listener is triggered after any inventory movement
            // and checks if the new level is below minimum
            if (!isset($event->level) || !$event->level instanceof InventoryLevel) {
                return;
            }

            $level = $event->level;
            if ($level->min_stock_level === null || $level->min_stock_level <= 0) {
                return;
            }

            if ($level->quantity_on_hand <= $level->min_stock_level) {
                ProductLowStock::dispatch(
                    $level->product,
                    $level,
                    $level->warehouse,
                );
            }
        } catch (\Throwable $e) {
            Log::error('CheckLowStockThreshold failed: ' . $e->getMessage());
        }
    }

    public function failed($event, \Throwable $exception): void
    {
        Log::critical('CheckLowStockThreshold PERMANENTLY FAILED', [
            'error' => $exception->getMessage(),
        ]);
    }
}
