<?php

declare(strict_types=1);

namespace App\Domain\Shared\Domain\Model;

readonly class FileUpload
{
    public function __construct(
        public string $id,
        public string $originalName,
        public string $path,
        public string $extension,
        public int $size,
        public \DateTimeImmutable $uploadedAt
    ) {
    }

    public static function create(
        string $originalName,
        string $path,
        int $size
    ): self {
        return new self(
            id: uniqid('file_', true),
            originalName: $originalName,
            path: $path,
            extension: strtolower(pathinfo($originalName, PATHINFO_EXTENSION)),
            size: $size,
            uploadedAt: new \DateTimeImmutable()
        );
    }

    public function isValidFormat(array $allowedExtensions): bool
    {
        return in_array($this->extension, $allowedExtensions, true);
    }

    public function getFormattedSize(int $precision = 2): string
    {
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];
        $bytes = max($this->size, 0);
        $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
        $pow = min($pow, count($units) - 1);
        $bytes /= (1 << (10 * $pow));

        return round($bytes, $precision) . ' ' . $units[$pow];
    }
}
