<?php

namespace App\Http\Controllers\Admin\Developer;

use App\Http\Controllers\Controller;
use App\Http\Requests\PaginatedRequest;
use App\Services\Admin\Developer\LogViewerService;
use Inertia\Inertia;
use Inertia\Response;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class LogController extends Controller
{
    public function __construct(
        private readonly LogViewerService $service,
    ) {}

    public function index(PaginatedRequest $request): Response
    {
        $files = $this->service->availableFiles();
        $file = $request->validated('file') ?: $files->first()['name'] ?? null;

        return Inertia::render('admin/developer/logs/index', [
            'entries' => $file
                ? $this->service->paginated(
                    $file,
                    ...$request->validatedWithDefaults(),
                    level: $request->validated('level'),
                )
                : null,
            'files' => $files,
            'selectedFile' => $file,
            'filters' => $request->only(['file', 'level']),
        ]);
    }

    public function download(PaginatedRequest $request): BinaryFileResponse
    {
        $file = $request->validated('file');

        abort_unless($file, 404);

        $files = $this->service->availableFiles();

        abort_unless($files->pluck('name')->contains($file), 404);

        return response()->download(storage_path('logs/'.$file));
    }
}
