<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Storage;

class SelfieController extends Controller
{
    public function show($filename)
    {
        $safeFilename = basename($filename);

        $candidates = array_values(array_unique([
            $filename,
            $safeFilename,
            'selfies/' . $safeFilename,
            ltrim($filename, '/'),
            ltrim($safeFilename, '/'),
        ]));

        foreach ($candidates as $candidate) {
            if (Storage::disk('public')->exists($candidate)) {
                $path = Storage::disk('public')->path($candidate);

                return response()->file($path, [
                    'Content-Type' => mime_content_type($path),
                    'Cache-Control' => 'max-age=86400, public',
                ]);
            }
        }

        abort(404, 'Selfie file not found.');
    }
}
