<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpAuditLogs\Pages;

use App\Filament\Resources\DberpAuditLogs\DberpAuditLogResource;
use App\Services\DberpAuditLogPruningService;
use App\Services\DberpPermissionService;
use App\Support\AuditLogDisplay\DberpAuditLogDisplayFormatter;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Contracts\Pagination\AbstractPaginator;
use Illuminate\Contracts\Pagination\CursorPaginator;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;

class ListDberpAuditLogs extends ListRecords
{
    protected static string $resource = DberpAuditLogResource::class;

    public function render(): View
    {
        $records = $this->getTableRecords();
        $logs = match (true) {
            $records instanceof AbstractPaginator => collect($records->items()),
            $records instanceof CursorPaginator => collect($records->items()),
            $records instanceof Collection => $records,
            default => collect(),
        };

        if ($logs->isNotEmpty()) {
            app(DberpAuditLogDisplayFormatter::class)->preloadRelationsForLogs($logs);
        }

        return parent::render();
    }

    protected function getHeaderActions(): array
    {
        return [
            Action::make('purgeExpiredAuditLogs')
                ->label(__('dberp.audit.purge_expired_action'))
                ->color('danger')
                ->requiresConfirmation()
                ->modalHeading(__('dberp.audit.purge_expired_modal_heading'))
                ->modalDescription(fn (): string => (string) __('dberp.audit.purge_expired_modal_description', [
                    'days' => config('dberp.audit.retention_days', 7),
                ]))
                ->visible(fn (): bool => app(DberpPermissionService::class)->allows(Auth::user(), DberpPermissionService::PURGE_AUDIT_LOG))
                ->action(function (DberpAuditLogPruningService $pruning): void {
                    $days = (int) config('dberp.audit.retention_days', 7);
                    $deleted = $pruning->deleteOlderThan($days);

                    if ($deleted === 0) {
                        Notification::make()
                            ->title(__('dberp.audit.purge_nothing_title'))
                            ->body((string) __('dberp.audit.purge_nothing_body', ['days' => $days]))
                            ->info()
                            ->send();

                        return;
                    }

                    Notification::make()
                        ->title(__('dberp.audit.purge_completed_title'))
                        ->body((string) __('dberp.audit.purge_completed_body', ['count' => $deleted, 'days' => $days]))
                        ->success()
                        ->send();
                }),
        ];
    }
}
