<?php

namespace App\Filament\Resources\RestoreRunResource\Pages;

use App\Filament\Resources\RestoreRunResource;
use App\Support\Filament\CanonicalAdminEnvironmentFilterState;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class ListRestoreRuns extends ListRecords
{
    protected static string $resource = RestoreRunResource::class;

    /**
     * @param  array<string, mixed>  $arguments
     * @param  array<string, mixed>  $context
     */
    public function mountAction(string $name, array $arguments = [], array $context = []): mixed
    {
        if (($context['table'] ?? false) === true && filled($context['recordKey'] ?? null) && in_array($name, ['archive', 'forceDelete', 'rerun'], true)) {
            try {
                RestoreRunResource::resolveScopedRecordOrFail($context['recordKey']);
            } catch (ModelNotFoundException) {
                abort(404);
            }
        }

        return parent::mountAction($name, $arguments, $context);
    }

    public function mount(): void
    {
        app(CanonicalAdminEnvironmentFilterState::class)->sync(
            $this->getTableFiltersSessionKey(),
            request: request(),
            environmentFilterName: null,
        );

        parent::mount();
    }

    private function tableHasRecords(): bool
    {
        return $this->getTableRecords()->count() > 0;
    }

    protected function getHeaderActions(): array
    {
        return [
            RestoreRunResource::makeCreateAction()
                ->visible(fn (): bool => $this->tableHasRecords()),
        ];
    }

    public function getSubheading(): ?string
    {
        return match (request()->string('recovery_posture_reason')->toString()) {
            'no_history' => 'No executed restore history is visible in the latest tenant restore records.',
            'failed' => 'The dashboard opened restore history because the latest executed restore failed and a specific detail is not available.',
            'partial' => 'The dashboard opened restore history because the latest executed restore completed partially and a specific detail is not available.',
            'completed_with_follow_up' => 'The dashboard opened restore history because skipped or non-applied work still needs follow-up.',
            'no_recent_issues_visible' => 'The dashboard opened restore history because no recent restore issues are visible, but tenant-wide recovery is still not proven.',
            default => null,
        };
    }
}
