<?php

namespace App\Filament\Resources\BackupScheduleResource\Pages;

use App\Filament\Resources\BackupScheduleResource;
use App\Support\BackupHealth\TenantBackupHealthAssessment;
use App\Support\BackupHealth\TenantBackupHealthResolver;
use App\Support\Filament\CanonicalAdminEnvironmentFilterState;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class ListBackupSchedules extends ListRecords
{
    protected static string $resource = BackupScheduleResource::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', 'restore', 'forceDelete'], true)) {
            try {
                BackupScheduleResource::resolveScopedRecordOrFail($context['recordKey']);
            } catch (ModelNotFoundException) {
                abort(404);
            }
        }

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

    public function mount(): void
    {
        $this->syncCanonicalAdminEnvironmentFilterState();

        parent::mount();
    }

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

    protected function getTableEmptyStateActions(): array
    {
        return [
            BackupScheduleResource::makeCreateAction(),
        ];
    }

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

    private function syncCanonicalAdminEnvironmentFilterState(): void
    {
        app(CanonicalAdminEnvironmentFilterState::class)->sync(
            $this->getTableFiltersSessionKey(),
            environmentSensitiveFilters: [],
            request: request(),
            environmentFilterName: null,
        );
    }

    public function getSubheading(): ?string
    {
        if (request()->string('backup_health_reason')->toString() !== TenantBackupHealthAssessment::REASON_SCHEDULE_FOLLOW_UP) {
            return null;
        }

        $tenant = BackupScheduleResource::panelTenantContext();

        if ($tenant === null) {
            return 'One or more enabled schedules need follow-up.';
        }

        /** @var TenantBackupHealthResolver $resolver */
        $resolver = app(TenantBackupHealthResolver::class);
        $summary = $resolver->assess($tenant)->scheduleFollowUp->summaryMessage;

        return $summary ?? 'One or more enabled schedules need follow-up.';
    }
}
