<?php

namespace App\Domain\Inventory\Listeners;

use App\Domain\Inventory\Events\InventoryMovementCreated;
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(InventoryMovementCreated $event): void
    {
        try {
            $level = $event->level;

            // Only check after outbound movements
            if ($event->movement->direction !== 'out') {
                return;
            }

            // Load the product relationship if not already loaded
            $level->loadMissing(['product', 'warehouse']);

            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(), [
                'movement_id' => $event->movement->id,
            ]);
        }
    }

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