<?php

namespace App\Filament\Central\Resources\TenantResource\Pages;

use App\Filament\Central\Pages\StorageSettings;
use App\Filament\Central\Resources\TenantResource;
use App\Services\Storage\StorageConfig;
use Filament\Actions\Action;
use Filament\Actions\CreateAction;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ListRecords;
use Filament\Support\Icons\Heroicon;
use Illuminate\Support\Facades\Artisan;

class ListTenants extends ListRecords
{
    protected static string $resource = TenantResource::class;

    protected function getHeaderActions(): array
    {
        return [
            CreateAction::make(),

            // The storage columns read cached counters, so a stale figure looks
            // identical to an accurate one. Recalculating belongs next to the
            // numbers it corrects rather than on the settings page.
            Action::make('recalculateStorage')
                ->label('Recalculate storage')
                ->icon(Heroicon::OutlinedArrowPath)
                ->color('gray')
                ->requiresConfirmation()
                ->modalDescription('Re-scans the bucket and refreshes every tenant\'s usage figures. On a large bucket this can take a while.')
                ->action(function (): void {
                    Artisan::call('storage:recalculate-usage');

                    Notification::make()
                        ->title('Storage usage recalculated')
                        ->success()
                        ->send();
                }),

            Action::make('storageSettings')
                ->label('Storage settings')
                ->icon(Heroicon::OutlinedCircleStack)
                ->color('gray')
                ->url(StorageSettings::getUrl()),
        ];
    }

    /**
     * Total consumption against the platform quota — the shared figure the
     * per-tenant rows are shares of.
     */
    public function getSubheading(): ?string
    {
        $used = StorageSettings::totalUsedBytes();
        $quota = app(StorageConfig::class)->quotaBytes();

        $total = TenantResource::formatBytes($used);

        if ($quota === null) {
            return $total.' of file storage used across all tenants (no platform quota set).';
        }

        return sprintf(
            '%s of %s platform storage used (%s%%).',
            $total,
            TenantResource::formatBytes($quota),
            number_format($quota > 0 ? $used / $quota * 100 : 0, 1),
        );
    }
}
