<?php

namespace Inside\DESK\Console;

use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Inside\DESK\Jobs\ComputeNewslettersStatistics;
use InvalidArgumentException;

class ComputeNewslettersStatisticsCommand extends Command
{
    /**
     * @var string
     */
    protected $signature = 'desk:statistics:newsletters
    {--from= : Calcul des statistiques depuis la newsletter de cette date. Format: Y-m-d}
    {--to= : Calcul des statistiques jusqu\'à la newsletter de cette date. Format: Y-m-d}';

    /**
     * @var string
     */
    protected $description = 'Regénération des statistiques des newsletters';

    /**
     * @return void
     */
    public function handle(): void
    {
        $from = $this->option('from');
        if (is_string($from)) {
            try {
                $from = Carbon::createFromFormat('Y-m-d', $from);
            } catch (InvalidArgumentException $e) {
                $from = null;
            }
        }

        $to = $this->option('to');
        if (is_string($to)) {
            try {
                $to = Carbon::createFromFormat('Y-m-d', $to);
            } catch (InvalidArgumentException $e) {
                $to = null;
            }
        }

        ComputeNewslettersStatistics::dispatchNow($from, $to, $this->getOutput());
    }
}
