<?php

namespace App\Support;

use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\StreamedResponse;

final class LocalMedia
{
    public const DISK = 'local';

    /**
     * @return array{path: string, original_name: string, mime_type: string, size: int}
     */
    public function store(string $directory, UploadedFile $file): array
    {
        $path = $file->store($directory, self::DISK);

        if (! is_string($path) || $path === '') {
            throw new \RuntimeException('Unable to store the uploaded file.');
        }

        return [
            'path' => $path,
            'original_name' => $file->getClientOriginalName(),
            'mime_type' => (string) ($file->getMimeType() ?: $file->getClientMimeType()),
            'size' => (int) $file->getSize(),
        ];
    }

    public function delete(?string $path): void
    {
        if (! filled($path)) {
            return;
        }

        Storage::disk(self::DISK)->delete($path);
    }

    public function response(string $path, string $name): StreamedResponse|BinaryFileResponse
    {
        abort_unless(Storage::disk(self::DISK)->exists($path), 404);

        return Storage::disk(self::DISK)->response($path, $name);
    }
}
