<?php

namespace App\Filament\Resources\AuditLogResource\Pages;

use App\Filament\Resources\AuditLogResource;
use App\Filament\Support\Perm;
use App\Models\AuditLog;
use App\Services\AuditLog as AuditLogService;
use Filament\Actions\Action;
use Filament\Resources\Pages\ListRecords;
use Symfony\Component\HttpFoundation\StreamedResponse;

class ListAuditLogs extends ListRecords
{
    protected static string $resource = AuditLogResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Action::make('export')
                ->label('Export CSV')
                ->color('gray')
                ->visible(fn (): bool => Perm::can('audit_logs', 'export'))
                ->action(fn () => $this->exportCsv()),
        ];
    }

    /**
     * Ported from AuditLogController::export(), including its own permission
     * guard (enforced here, not only on the button), the same 1000-row cap, and
     * the same column set. The export honours the table's active filters, which
     * is what the source's "both go through filteredQuery()" comment intends.
     */
    public function exportCsv(): StreamedResponse
    {
        abort_unless(Perm::can('audit_logs', 'export'), 403);

        $logs = $this->getFilteredTableQuery()
            ->orderByDesc('created_at')
            ->limit(1000)
            ->get();

        return response()->streamDownload(function () use ($logs): void {
            $out = fopen('php://output', 'w');
            fputcsv($out, ['When', 'Actor', 'Email', 'Action', 'Description', 'IP', 'Subject Type', 'Subject ID']);
            foreach ($logs as $log) {
                /** @var AuditLog $log */
                fputcsv($out, [
                    $log->created_at?->toDateTimeString(),
                    $log->actor?->name ?? 'System',
                    $log->actor?->email ?? '',
                    $log->action,
                    $log->description ?: AuditLogService::describe($log),
                    $log->ip,
                    $log->subject_type,
                    $log->subject_id,
                ]);
            }
            fclose($out);
        }, 'audit-logs.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
    }
}
