<?php

namespace App\Console\Commands;

use App\Services\InventoryLowStockQuery;
use Illuminate\Console\Command;

class InventoryAlertLowStockCommand extends Command
{
    protected $signature = 'inventory:alert-low-stock
                            {--threshold= : Umbral global si el producto no tiene min_stock (por defecto config inventory.low_stock.default_threshold)}';

    protected $description = 'Lista SKU de inventario (almacén) con stock en o por debajo del mínimo efectivo.';

    public function handle(InventoryLowStockQuery $query): int
    {
        $threshold = $this->option('threshold');
        if ($threshold === null || $threshold === '') {
            $threshold = (string) config('inventory.low_stock.default_threshold');
        }

        if (! is_numeric($threshold)) {
            $this->error('El umbral debe ser numérico.');

            return self::FAILURE;
        }

        $rows = $query->collect($threshold);

        if ($rows->isEmpty()) {
            $this->info('Sin productos bajo mínimo (umbral global: '.$threshold.').');

            return self::SUCCESS;
        }

        $this->warn('Productos con stock bajo ('.$rows->count().'):');
        $table = $rows->map(function ($p) use ($threshold) {
            $minEff = $p->min_stock !== null
                ? (string) $p->min_stock
                : $threshold;

            return [
                $p->sku,
                $p->name,
                (string) $p->stock_quantity,
                $minEff,
            ];
        })->all();

        $this->table(['SKU', 'Nombre', 'Stock', 'Mín. efectivo'], $table);

        return self::SUCCESS;
    }
}
