<?php

namespace App\Http\Middleware;

use App\Services\ImageUploadOptimizer;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Response;

class OptimizeUploadedImages
{
    public function __construct(private ImageUploadOptimizer $optimizer)
    {
    }

    public function handle(Request $request, Closure $next): Response
    {
        if ($request->files->count() === 0) {
            return $next($request);
        }

        try {
            $request->files->replace($this->optimizeFiles($request->files->all()));

            return $next($request);
        } finally {
            $this->optimizer->cleanup();
        }
    }

    private function optimizeFiles(array $files): array
    {
        foreach ($files as $key => $file) {
            if ($file instanceof UploadedFile) {
                $files[$key] = $this->optimizer->optimize($file);
                continue;
            }

            if (is_array($file)) {
                $files[$key] = $this->optimizeFiles($file);
            }
        }

        return $files;
    }
}
