<?php

declare(strict_types=1);

namespace Core;

final class Upload
{
    public static function store(array $file, string $directory, array $allowedMimeTypes, int $maxSizeMb = 5): array
    {
        $error = Validator::file($file, $allowedMimeTypes, $maxSizeMb);
        if ($error) throw new \RuntimeException($error);

        $finfo = new \finfo(FILEINFO_MIME_TYPE);
        $mime = $finfo->file($file['tmp_name']);
        $extension = match ($mime) {
            'image/jpeg' => 'jpg',
            'image/png' => 'png',
            'application/pdf' => 'pdf',
            default => pathinfo($file['name'], PATHINFO_EXTENSION) ?: 'bin',
        };

        $relativeDir = trim($directory, '/') . '/' . date('Y/m');
        $absoluteDir = dirname(__DIR__) . '/storage/' . $relativeDir;
        if (!is_dir($absoluteDir)) mkdir($absoluteDir, 0775, true);

        $storedName = bin2hex(random_bytes(20)) . '.' . $extension;
        $absolutePath = $absoluteDir . '/' . $storedName;
        if (!move_uploaded_file($file['tmp_name'], $absolutePath)) throw new \RuntimeException('Não foi possível salvar o arquivo.');

        return [
            'original_name' => $file['name'],
            'stored_name' => $storedName,
            'relative_path' => $relativeDir . '/' . $storedName,
            'mime_type' => $mime,
            'size_bytes' => (int)$file['size'],
        ];
    }
}
