<?php

namespace App\Filament\Pages;

use App\Services\Settings\SettingsService;
use App\Services\System\SystemHealthService;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Filament\Support\Enums\Width;
use Filament\Support\Icons\Heroicon;
use Illuminate\Support\Facades\Artisan;

class SystemHealth extends Page
{
    protected static string|BackedEnum|null $navigationIcon = Heroicon::Bolt;

    protected static ?string $navigationLabel = 'System Health';

    protected static string|\UnitEnum|null $navigationGroup = 'Operations';

    protected static ?int $navigationSort = 5;

    protected string $view = 'filament.pages.system-health';

    protected Width|string|null $maxContentWidth = Width::Full;

    /**
     * @return array<int, Action>
     */
    protected function getHeaderActions(): array
    {
        return [
            Action::make('recordHeartbeat')
                ->label('Record heartbeat')
                ->icon(Heroicon::ArrowPath)
                ->color('gray')
                ->action(function (SystemHealthService $health): void {
                    $health->recordSchedulerHeartbeat();

                    Notification::make()
                        ->success()
                        ->title('Scheduler heartbeat recorded')
                        ->send();
                }),

            Action::make('clearCaches')
                ->label('Clear caches')
                ->icon(Heroicon::Trash)
                ->color('warning')
                ->requiresConfirmation()
                ->action(function (): void {
                    Artisan::call('optimize:clear');
                    app(SettingsService::class)->clearCache();

                    Notification::make()
                        ->success()
                        ->title('Application caches cleared')
                        ->send();
                }),
        ];
    }

    /**
     * @return array<string, mixed>
     */
    protected function getViewData(): array
    {
        $health = app(SystemHealthService::class);
        $checks = collect($health->checks());

        return [
            'summary' => $health->summary(),
            'groups' => $checks->groupBy('group'),
        ];
    }
}
