<?php

declare(strict_types=1);

namespace app\common\library\upload;

use Webman\Http\UploadFile;

/**
 * Webman UploadFile 适配器，提供 ThinkPHP UploadedFile 兼容接口
 */
class WebmanUploadedFile
{
    public function __construct(
        protected UploadFile $file
    ) {
    }

    public function extension(): string
    {
        $ext = $this->file->getUploadExtension();
        return $ext && preg_match("/^[a-zA-Z0-9]+$/", $ext) ? $ext : 'file';
    }

    public function getMime(): string
    {
        return $this->file->getUploadMimeType() ?? '';
    }

    public function getSize(): int
    {
        $size = $this->file->getSize();
        return $size !== false ? $size : 0;
    }

    public function getOriginalName(): string
    {
        return $this->file->getUploadName() ?? '';
    }

    public function sha1(): string
    {
        $path = $this->file->getPathname();
        return is_file($path) ? hash_file('sha1', $path) : '';
    }

    public function getPathname(): string
    {
        return $this->file->getPathname();
    }

    /**
     * 移动文件（兼容 ThinkPHP move($dir, $name) 与 Webman move($fullPath)）
     */
    public function move(string $directory, ?string $name = null): self
    {
        $destination = rtrim($directory, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . ($name ?? basename($this->file->getUploadName()));
        $this->file->move($destination);
        return $this;
    }

    public function getUploadFile(): UploadFile
    {
        return $this->file;
    }
}
