<?php declare(strict_types=1);

namespace App\Service;

use Doctrine\Common\Collections\ArrayCollection;

class SizeFormatter
{
    /**
     * Calculate the total size of files in a collection and format it.
     *
     * @param ArrayCollection $files The collection of files.
     * @return string The total size formatted in KB or MB.
     */
    public function calculateTotalSize(ArrayCollection $files): string
    {
        $totalSizeInBytes = 0;

        foreach ($files as $file) {
            $fileSize = $file->getSize();

            if (is_numeric($fileSize)) {
                $totalSizeInBytes += $fileSize;
            }
        }

        return $this->formatSize($totalSizeInBytes);
    }

    /**
     * Format a size in bytes to KB or MB.
     *
     * @param int $sizeInBytes The size in bytes to format.
     * @return string The formatted size with units (KB or MB).
     */
    public function formatSize(int $sizeInBytes): string
    {
        if ($sizeInBytes >= 1048576) {
            return number_format($sizeInBytes / 1048576, 2) . ' MB';
        }

        return number_format($sizeInBytes / 1024, 2) . ' KB';
    }
}
