<?php

namespace App\Http\Controllers;

use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class PublicStorageController extends Controller
{
    /**
     * Serve safe public uploads when cPanel symbolic links are unavailable.
     */
    public function show(string $path): BinaryFileResponse|Response
    {
        abort_if(str_contains($path, '..'), 404);

        $allowedPrefixes = [
            'profile-photos/',
            'trade-screenshots/',
            'lead-magnets/',
            'report-logos/',
            'avatars/',
            'community-posts/',
        ];

        $isAllowed = collect($allowedPrefixes)->contains(
            fn (string $prefix): bool => str_starts_with($path, $prefix)
        );

        abort_unless($isAllowed, 404);
        abort_unless(Storage::disk('public')->exists($path), 404);

        return response()->file(Storage::disk('public')->path($path), [
            'Cache-Control' => 'public, max-age=604800',
        ]);
    }
}
