<?php

namespace App\Console\Commands;

use App\Models\DailyMetricSnapshot;
use App\Models\Solicitor\Solicitor;
use App\Services\Dashboard\DashboardMetrics;
use Illuminate\Console\Command;

/**
 * Captures the current value of every stock/backlog dashboard metric for each
 * solicitor, once per day (scheduled at 5pm). The dashboard reads these back to
 * show whether those backlogs (Missing ID/POA, Investigation, Care Settings,
 * Emails Outstanding, etc.) are trending down over time.
 *
 * Runs in the console, where the BelongsToSolicitor global scope is disabled, so
 * it loops solicitors explicitly and DashboardMetrics filters solicitor_id
 * directly. Idempotent: re-running on the same day overwrites that day's rows.
 */
class SnapshotDailyMetrics extends Command
{
    protected $signature = 'dashboard:snapshot-metrics {--date= : Capture date (Y-m-d), defaults to today}';

    protected $description = 'Capture a daily snapshot of stock/backlog dashboard metrics per solicitor.';

    public function handle(): int
    {
        $capturedOn = $this->option('date')
            ? \Illuminate\Support\Carbon::parse($this->option('date'))->toDateString()
            : now()->toDateString();

        $solicitors = Solicitor::query()->get(['id']);
        $rows       = 0;

        foreach ($solicitors as $solicitor) {
            $metrics = new DashboardMetrics($solicitor->id);

            foreach ($metrics->snapshotValues() as $metric => $value) {
                DailyMetricSnapshot::updateOrCreate(
                    [
                        'solicitor_id' => $solicitor->id,
                        'captured_on'  => $capturedOn,
                        'metric'       => $metric,
                    ],
                    ['value' => $value],
                );
                $rows++;
            }
        }

        $this->info("Captured {$rows} metric snapshot(s) for {$solicitors->count()} solicitor(s) on {$capturedOn}.");

        return self::SUCCESS;
    }
}
