<?php

declare(strict_types=1);

namespace App\Filament\Widgets\Dashboard;

use App\Filament\Pages\DriftLanding;
use App\Filament\Resources\FindingResource;
use App\Models\Finding;
use App\Models\OperationRun;
use App\Models\Tenant;
use App\Support\OperationRunLinks;
use App\Support\OpsUx\ActiveRuns;
use Filament\Facades\Filament;
use Filament\Widgets\Widget;

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

    protected string $view = 'filament.widgets.dashboard.needs-attention';

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

        if (! $tenant instanceof Tenant) {
            return [
                'pollingInterval' => null,
                'items' => [],
                'healthyChecks' => [],
            ];
        }

        $tenantId = (int) $tenant->getKey();

        $items = [];

        $highSeverityCount = (int) Finding::query()
            ->where('tenant_id', $tenantId)
            ->where('finding_type', Finding::FINDING_TYPE_DRIFT)
            ->where('status', Finding::STATUS_NEW)
            ->where('severity', Finding::SEVERITY_HIGH)
            ->count();

        if ($highSeverityCount > 0) {
            $items[] = [
                'title' => 'High severity drift findings',
                'body' => "{$highSeverityCount} finding(s) need review.",
                'url' => FindingResource::getUrl('index', tenant: $tenant),
                'badge' => 'Drift',
                'badgeColor' => 'danger',
            ];
        }

        $latestDriftSuccess = OperationRun::query()
            ->where('tenant_id', $tenantId)
            ->where('type', 'drift.generate')
            ->where('status', 'completed')
            ->where('outcome', 'succeeded')
            ->whereNotNull('completed_at')
            ->latest('completed_at')
            ->first();

        if (! $latestDriftSuccess) {
            $items[] = [
                'title' => 'No drift scan yet',
                'body' => 'Generate drift after you have at least two successful inventory runs.',
                'url' => DriftLanding::getUrl(tenant: $tenant),
                'badge' => 'Drift',
                'badgeColor' => 'warning',
            ];
        } else {
            $isStale = $latestDriftSuccess->completed_at?->lt(now()->subDays(7)) ?? true;

            if ($isStale) {
                $items[] = [
                    'title' => 'Drift stale',
                    'body' => 'Last drift scan is older than 7 days.',
                    'url' => DriftLanding::getUrl(tenant: $tenant),
                    'badge' => 'Drift',
                    'badgeColor' => 'warning',
                ];
            }
        }

        $latestDriftFailure = OperationRun::query()
            ->where('tenant_id', $tenantId)
            ->where('type', 'drift.generate')
            ->where('status', 'completed')
            ->where('outcome', 'failed')
            ->latest('id')
            ->first();

        if ($latestDriftFailure instanceof OperationRun) {
            $items[] = [
                'title' => 'Drift generation failed',
                'body' => 'Investigate the latest failed run.',
                'url' => OperationRunLinks::view($latestDriftFailure, $tenant),
                'badge' => 'Operations',
                'badgeColor' => 'danger',
            ];
        }

        $activeRuns = (int) OperationRun::query()
            ->where('tenant_id', $tenantId)
            ->active()
            ->count();

        if ($activeRuns > 0) {
            $items[] = [
                'title' => 'Operations in progress',
                'body' => "{$activeRuns} run(s) are active.",
                'url' => OperationRunLinks::index($tenant),
                'badge' => 'Operations',
                'badgeColor' => 'warning',
            ];
        }

        $items = array_slice($items, 0, 5);

        $healthyChecks = [];

        if ($items === []) {
            $healthyChecks = [
                [
                    'title' => 'Drift findings look healthy',
                    'body' => 'No high severity drift findings are open.',
                    'url' => FindingResource::getUrl('index', tenant: $tenant),
                    'linkLabel' => 'View findings',
                ],
                [
                    'title' => 'Drift scans are up to date',
                    'body' => $latestDriftSuccess?->completed_at
                        ? 'Last drift scan: '.$latestDriftSuccess->completed_at->diffForHumans(['short' => true]).'.'
                        : 'Drift scan history is available in Drift.',
                    'url' => DriftLanding::getUrl(tenant: $tenant),
                    'linkLabel' => 'Open Drift',
                ],
                [
                    'title' => 'No active operations',
                    'body' => 'Nothing is currently running for this tenant.',
                    'url' => OperationRunLinks::index($tenant),
                    'linkLabel' => 'View operations',
                ],
            ];
        }

        return [
            'pollingInterval' => ActiveRuns::existForTenant($tenant) ? '10s' : null,
            'items' => $items,
            'healthyChecks' => $healthyChecks,
        ];
    }
}
