<?php

namespace App\Console\Commands;

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

class RanchNotifyCalvingReportCommand extends Command
{
    protected $signature = 'ranch:notify-calving-report
                            {--from= : Fecha inicio (Y-m-d)}
                            {--to= : Fecha fin (Y-m-d)}
                            {--previous-month : Mes calendario anterior completo (default sin fechas)}';

    protected $description = 'Envía por correo el resumen de partos del periodo';

    public function handle(RanchCalvingReportNotificationService $service): int
    {
        $filters = array_filter([
            'from' => $this->option('from'),
            'to' => $this->option('to'),
            'pasture_id' => null,
        ], fn ($v) => $v !== null && $v !== '');

        $usePreviousMonth = (bool) $this->option('previous-month')
            || (! isset($filters['from']) && ! isset($filters['to']));

        $result = $service->send($filters, $usePreviousMonth);

        $this->info($result['message']);
        if ($result['from'] || $result['to']) {
            $this->line('Periodo: '.($result['from'] ?? '—').' → '.($result['to'] ?? '—'));
        }
        $this->line('Partos: '.$result['calvings_count']);
        if ($result['recipients'] !== []) {
            $this->line('Destinatarios: '.implode(', ', $result['recipients']));
        }

        return $result['sent'] ? self::SUCCESS : self::FAILURE;
    }
}
