<?php

namespace App\Console\Commands;

use App\Contracts\StatsModel;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\App;
use Mtc\MercuryDataModels\ReportingStat;

class GenerateReportingStats extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'stats:generate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate Stats for previous day';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        collect(config('automotive.stats-types', []))
            ->map(fn ($class) => App::make($class))
            ->filter(fn ($stats_model) => $stats_model instanceof StatsModel)
            ->each(fn (StatsModel $stats_model) => $this->storeAndFetch($stats_model));

        return 0;
    }

    private function storeAndFetch(StatsModel $stats_model)
    {
        $date = Carbon::yesterday();
        ReportingStat::query()
            ->updateOrCreate([
                'key' => $stats_model->getKey(),
                'date' => $date->format('Y-m-d'),
            ], [
                'value' => $stats_model->getValue($date),
            ]);
    }
}
