<?php

namespace App\Filament\Pages;

use App\Serp\Operations\KillSwitch;
use App\Serp\Operations\SerpOperationsMetrics;
use BackedEnum;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Filament\Support\Icons\Heroicon;

class SerpOperations extends Page
{
    protected string $view = 'filament.pages.serp-operations';

    protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedShieldCheck;

    public static function getNavigationLabel(): string
    {
        return __('ui.serp_operations');
    }

    public function getTitle(): string
    {
        return __('ui.serp_operations');
    }

    public array $summary = [];

    public static function canAccess(): bool
    {
        return auth()->user()?->hasPermission('serp_operations.view') ?? false;
    }

    public function mount(SerpOperationsMetrics $metrics): void
    {
        $this->summary = $metrics->summary();
    }

    public function emergencyStop(KillSwitch $kill): void
    {
        $this->authorizeManage();
        $kill->activate('manual_emergency_stop', auth()->user());
        $this->summary = app(SerpOperationsMetrics::class)->summary();
        Notification::make()->title(__('operations.stopped'))->warning()->send();
    }

    public function clearEmergencyStop(KillSwitch $kill): void
    {
        $this->authorizeManage();
        $kill->clear(auth()->user(), 'manual_clear');
        $this->summary = app(SerpOperationsMetrics::class)->summary();
        Notification::make()->title(__('operations.resumed'))->success()->send();
    }

    private function authorizeManage(): void
    {
        abort_unless(auth()->user()?->hasRole('super_admin') && auth()->user()?->hasPermission('serp_operations.emergency_stop'), 403);
    }
}
