<?php

namespace App\Traits;

use Exception;
use Illuminate\Support\Facades\Storage;

trait RemoveArchiveS3
{
    /**
     * Delete a file and return a boolean if succeded.
     *
     * @param string $url
     * @return bool
     * @throws \Exception If the file as not found or if the deletion failed.
     */
    public function removeArchiveByUrl(string $url): bool
    {
        // Extrair o caminho relativo da URL completa
        $imagePath = parse_url($url, PHP_URL_PATH);
        $imagePath = ltrim($imagePath, '/'); // remover a barra inicial

        // Excluir a imagem antiga
        if (Storage::exists($imagePath)) {
            $success = Storage::delete($imagePath);
            if ($success) {
                return true;
            } else {
                throw new Exception("Deletion was not possible");
            }
        } else {
            throw new Exception("File not found");
        }
    }
}
