<?php

namespace App\Traits;

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

trait RemoveArchiveS3
{
    /**
     * Delete a file and return a boolean if succeded.
     *
     * @throws \Exception If the file as not found or if the deletion failed.
     */
    public function removeArchiveByPath(string $path): bool
    {
        $exists = Storage::exists($path);

        Log::warning('[avatar-upload] RemoveArchiveS3::removeArchiveByPath', [
            'path'   => $path,
            'exists' => $exists,
        ]);

        if (! $exists) {
            Log::warning('[avatar-upload] Arquivo antigo NÃO encontrado no S3 para remoção', ['path' => $path]);
            return false;
        }

        $deleted = Storage::delete($path);

        Log::warning('[avatar-upload] Resultado da remoção do arquivo antigo', [
            'path'    => $path,
            'deleted' => $deleted,
        ]);

        if (! $deleted) {
            throw new Exception('Deletion was not possible');
        }

        return true;
    }
}
