<?php

declare(strict_types=1);

namespace App\Framework\LiveComponents\ValueObjects;

use App\Framework\Core\ValueObjects\Byte;
use App\Framework\Http\UploadedFile;

/**
 * Value Object representing a file uploaded through a LiveComponent
 */
final readonly class UploadedComponentFile
{
    public function __construct(
        public string $name,
        public string $type,
        public Byte $size,
        public string $tmpPath,
        public ?string $error = null
    ) {
    }

    public static function fromUploadedFile(UploadedFile $file): self
    {
        return new self(
            name: $file->getClientFilename(),
            type: $file->getClientMediaType(),
            size: Byte::fromBytes($file->getSize()),
            tmpPath: $file->getStream()->getMetadata('uri'),
            error: $file->getError() > 0 ? (string) $file->getError() : null
        );
    }

    public function isValid(): bool
    {
        return $this->error === null && file_exists($this->tmpPath);
    }

    public function toArray(): array
    {
        return [
            'name' => $this->name,
            'type' => $this->type,
            'size' => $this->size->toBytes(),
            'size_human' => $this->size->toHumanReadable(),
            'tmp_path' => $this->tmpPath,
            'error' => $this->error,
        ];
    }
}
