<?php
declare(strict_types=1);

function validateUploadedFile(array $file, array $allowedMimeToExtension, int $maxBytes): string
{
    if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
        throw new RuntimeException('File upload failed');
    }

    if (($file['size'] ?? 0) <= 0 || (int)$file['size'] > $maxBytes) {
        throw new RuntimeException('Uploaded file exceeds the allowed size');
    }

    $tmpName = (string)($file['tmp_name'] ?? '');
    if ($tmpName === '' || !is_uploaded_file($tmpName)) {
        throw new RuntimeException('Invalid uploaded file');
    }

    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mimeType = $finfo->file($tmpName) ?: '';

    if (!isset($allowedMimeToExtension[$mimeType])) {
        throw new RuntimeException('Unsupported uploaded file type');
    }

    return $allowedMimeToExtension[$mimeType];
}

function ensureUploadDirectory(string $directory): void
{
    if (!is_dir($directory) && !mkdir($directory, 0775, true) && !is_dir($directory)) {
        throw new RuntimeException('Unable to create upload directory');
    }
}

function randomUploadName(string $prefix, string $extension): string
{
    return sprintf('%s_%s_%s.%s', $prefix, date('YmdHis'), bin2hex(random_bytes(8)), $extension);
}
