<?php

namespace App\Domain\Inventory\Listeners;

use App\Domain\Inventory\Events\ProductLowStock;
use App\Domain\Notification\Services\NotificationService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;

class NotifyAdminLowStock implements ShouldQueue
{
    public function __construct(
        private NotificationService $notificationService,
    ) {}

    public function handle(ProductLowStock $event): void
    {
        try {
            $this->notificationService->sendToRole(
                type: 'product_low_stock',
                role: 'branch_manager',
                data: [
                    'product_name' => $event->product->name_ar,
                    'sku' => $event->product->sku,
                    'current_quantity' => $event->level->quantity_on_hand,
                    'min_stock' => $event->level->min_stock_level,
                    'warehouse_name' => $event->warehouse->name_ar,
                ],
                priority: 'high',
            );
        } catch (\Throwable $e) {
            Log::error('NotifyAdminLowStock failed: ' . $e->getMessage(), [
                'product_id' => $event->product->id,
            ]);
        }
    }

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