<?php
declare(strict_types=1);

namespace CronJobs;

use App\Core\Database;
use App\Core\Logger;
use App\Core\EventBus;

/**
 * Daily: alerts items below minimum stock level.
 */
class LowStockAlertJob
{
    private Database $db;
    public function __construct(Database $db) { $this->db = $db; }

    public function shouldRun(): bool
    {
        return true; // Runs daily
    }

    public function run(): array
    {
        $lowStockItems = \App\Modules\Inventory\Models\ItemWarehouseStock::getLowStockItems();
        $count = count($lowStockItems);

        foreach ($lowStockItems as $item) {
            EventBus::dispatch('inventory.low_stock_alert', [
                'item_id'      => (int) $item['item_id'],
                'warehouse_id' => (int) $item['warehouse_id'],
                'item_name'    => $item['name_ar'] ?? '',
                'quantity'     => $item['quantity'],
                'min_level'    => $item['min_level'],
            ]);
        }

        if ($count > 0) {
            Logger::info("Low stock alert: {$count} item(s) below minimum level");
        }

        return ['low_stock_items' => $count];
    }
}
