<?php

namespace App\Console\Commands;

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

class RanchNotifyOpenLotsGdpAlertsCommand extends Command
{
    protected $signature = 'ranch:notify-open-lots-gdp-alerts
                            {--force : Enviar aunque no haya alertas}
                            {--min-gdp= : Umbral GDP por defecto kg/día}
                            {--days= : Días sin pesaje para alerta}';

    protected $description = 'Envía correo si hay lotes de engorda abiertos con GDP bajo meta';

    public function handle(RanchOpenLotsGdpAlertNotificationService $service): int
    {
        $minGdp = $this->option('min-gdp') !== null ? (float) $this->option('min-gdp') : null;
        $days = $this->option('days') !== null ? (int) $this->option('days') : null;
        $force = (bool) $this->option('force');

        $result = $service->sendIfNeeded($minGdp, $days, $force);

        $this->info($result['message']);
        if ($result['recipients'] !== []) {
            $this->line('Destinatarios: '.implode(', ', $result['recipients']));
        }
        $this->line('Lotes con alerta: '.$result['lots_with_alerts_count']);
        $this->line('Animales en alerta: '.$result['animal_alerts_count']);

        return $result['sent'] || $result['lots_with_alerts_count'] === 0 ? self::SUCCESS : self::FAILURE;
    }
}
