<?php

namespace App\Console\Commands;

use App\Reporting\StatsModels\EnquiryUtmBreakdown;
use Carbon\Carbon;
use Illuminate\Console\Command;

class GenerateEnquiryUtmStats extends Command
{
    /**
     * @var string
     */
    protected $signature = 'stats:generate-utm
        {--date= : Aggregate a specific day (Y-m-d), defaults to yesterday}
        {--days= : Backfill the last N complete days}';

    /**
     * @var string
     */
    protected $description = 'Aggregate enquiry UTM attribution into reporting stats';

    public function handle(EnquiryUtmBreakdown $breakdown): int
    {
        foreach ($this->datesToProcess() as $date) {
            $breakdown->generate($date);
        }

        return self::SUCCESS;
    }

    /**
     * @return Carbon[]
     */
    private function datesToProcess(): array
    {
        if ($this->option('days')) {
            return collect(range(1, (int) $this->option('days')))
                ->map(fn ($daysAgo) => Carbon::today()->subDays($daysAgo))
                ->all();
        }

        return [
            $this->option('date')
                ? Carbon::parse($this->option('date'))
                : Carbon::yesterday(),
        ];
    }
}
