<?php
namespace app\adminapi\service\material\storage;

use think\facade\Filesystem;

class LocalStorage implements StorageInterface
{
    public function put($file, string $keyPrefix = ''): array
    {
        // 使用 public 磁盘：public/storage
        $path = Filesystem::disk('public')->putFile(trim($keyPrefix ?: 'material', '/'), $file);
        $urlPrefix = (string)config('filesystem.disks.public.url', '/storage');
        $url = rtrim($urlPrefix, '/') . '/' . ltrim($path, '/');
        return ['key' => $path, 'url' => $url];
    }

    public function delete(string $key): void
    {
        try {
            Filesystem::disk('public')->delete($key);
        } catch (\Throwable $e) {
            // 忽略物理删除失败
        }
    }

    public function url(string $key): string
    {
        $urlPrefix = (string)config('filesystem.disks.public.url', '/storage');
        return rtrim($urlPrefix, '/') . '/' . ltrim($key, '/');
    }
}
