<?php

namespace App\Framework\Http;

final readonly class UploadedFiles
{
    /** @var array<string, UploadedFile|UploadedFile[]> */
    private array $files;

    public function __construct(array $filesArray)
    {
        $this->files = array_map(function ($fileSpec) {
            return is_array($fileSpec['name'])
                ? $this->createMultipleFiles($fileSpec)
                : $this->createSingleFile($fileSpec);
        }, $filesArray);
    }

    private function createSingleFile(array $fileSpec): UploadedFile
    {
        return new UploadedFile(
            $fileSpec['name'] ?? '',
            $fileSpec['type'] ?? '',
            $fileSpec['size'] ?? 0,
            $fileSpec['tmp_name'] ?? '',
            UploadError::fromUploadError($fileSpec['error'] ?? UPLOAD_ERR_NO_FILE),
        );
    }

    private function createMultipleFiles(array $fileSpec): array
    {
        return array_map(
            fn($index) => new UploadedFile(
                $fileSpec['name'][$index] ?? '',
                $fileSpec['type'][$index] ?? '',
                $fileSpec['size'][$index] ?? 0,
                $fileSpec['tmp_name'][$index] ?? '',
                UploadError::fromUploadError($fileSpec['error'][$index] ?? UPLOAD_ERR_NO_FILE),
            ),
            array_keys($fileSpec['name'])
        );
    }

    public function get(string $key): ?UploadedFile
    {
        return $this->files[$key] ?? null;
    }

    /**
     * @return array<string, UploadedFile|UploadedFile[]>
     */
    public function all(): array
    {
        return $this->files;
    }
}
