<?php

declare(strict_types=1);

namespace App\Filament\Widgets\Dashboard;

use App\Filament\Pages\BaselineCompareLanding;
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 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',
            ];
        }

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

        if (! $latestBaselineCompareSuccess) {
            $items[] = [
                'title' => 'No baseline compare yet',
                'body' => 'Run a baseline compare after your tenant has an assigned baseline snapshot.',
                'url' => BaselineCompareLanding::getUrl(tenant: $tenant),
                'badge' => 'Drift',
                'badgeColor' => 'warning',
            ];
        } else {
            $isStale = $latestBaselineCompareSuccess->completed_at?->lt(now()->subDays(7)) ?? true;

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

        $latestBaselineCompareFailure = OperationRun::query()
            ->where('tenant_id', $tenantId)
            ->where('type', 'baseline_compare')
            ->where('status', 'completed')
            ->where('outcome', 'failed')
            ->latest('id')
            ->first();

        if ($latestBaselineCompareFailure instanceof OperationRun) {
            $items[] = [
                'title' => 'Baseline compare failed',
                'body' => 'Investigate the latest failed run.',
                'url' => OperationRunLinks::view($latestBaselineCompareFailure, $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' => 'Baseline compares are up to date',
                    'body' => $latestBaselineCompareSuccess?->completed_at
                        ? 'Last baseline compare: '.$latestBaselineCompareSuccess->completed_at->diffForHumans(['short' => true]).'.'
                        : 'Baseline compare history is available in Baseline Compare.',
                    'url' => BaselineCompareLanding::getUrl(tenant: $tenant),
                    'linkLabel' => 'Open Baseline Compare',
                ],
                [
                    '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,
        ];
    }
}
