<?php

namespace App\Support;

use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
use RuntimeException;

class PublicUploader
{
    public static function store(UploadedFile|TemporaryUploadedFile $file, string $directory): string
    {
        $directory = trim($directory, '/');
        $targetDirectory = public_path('uploads/'.$directory);

        if (! File::isDirectory($targetDirectory) && ! File::makeDirectory($targetDirectory, 0775, true)) {
            throw new RuntimeException("No se pudo crear el directorio de carga: {$targetDirectory}");
        }

        $extension = strtolower($file->getClientOriginalExtension() ?: $file->extension() ?: 'jpg');
        $filename = Str::uuid().'.'.$extension;

        $file->move($targetDirectory, $filename);

        return 'uploads/'.$directory.'/'.$filename;
    }

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

        if (str_starts_with($path, 'uploads/')) {
            File::delete(public_path($path));

            return;
        }

        Storage::disk('public')->delete($path);
    }
}
