<?php

declare(strict_types=1);

namespace App\Filament\Widgets\Tenant;

use App\Models\Tenant;
use App\Support\Baselines\BaselineCompareStats;
use App\Support\OperationRunLinks;
use Filament\Facades\Filament;
use Filament\Widgets\Widget;

class BaselineCompareCoverageBanner extends Widget
{
    protected static bool $isLazy = false;

    protected string $view = 'filament.widgets.tenant.baseline-compare-coverage-banner';

    /**
     * @return array<string, mixed>
     */
    protected function getViewData(): array
    {
        $tenant = Filament::getTenant();

        if (! $tenant instanceof Tenant) {
            return [
                'shouldShow' => false,
            ];
        }

        $stats = BaselineCompareStats::forTenant($tenant);

        $uncoveredTypes = $stats->uncoveredTypes ?? [];
        $uncoveredTypes = is_array($uncoveredTypes) ? $uncoveredTypes : [];

        $coverageStatus = $stats->coverageStatus;
        $hasWarnings = in_array($coverageStatus, ['warning', 'unproven'], true) && $uncoveredTypes !== [];

        $runUrl = null;

        if ($stats->operationRunId !== null) {
            $runUrl = OperationRunLinks::view($stats->operationRunId, $tenant);
        }

        return [
            'shouldShow' => $hasWarnings && $runUrl !== null,
            'runUrl' => $runUrl,
            'coverageStatus' => $coverageStatus,
            'fidelity' => $stats->fidelity,
            'uncoveredTypesCount' => $stats->uncoveredTypesCount ?? count($uncoveredTypes),
            'uncoveredTypes' => $uncoveredTypes,
        ];
    }
}
