<?php

namespace App\Traits;

use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

trait UploadsFile
{
    public function uploadFile(UploadedFile $file, string $folder, ?string $filename = null): string
    {
        $extension = $file->getClientOriginalExtension();
        $name      = $filename ?? Str::random(20).'.'.$extension;
        $path      = $folder.'/'.$name;

        Log::warning('[avatar-upload] UploadsFile::uploadFile — chamando Storage::disk(s3)->put()', [
            'path'           => $path,
            'disk'           => 's3',
            'file_size'      => $file->getSize(),
            'file_real_path' => $file->getRealPath(),
            'content_length' => strlen(file_get_contents($file)),
        ]);

        $result = Storage::disk('s3')->put($path, file_get_contents($file));

        Log::warning('[avatar-upload] UploadsFile::uploadFile — resultado do Storage::put()', [
            'path'           => $path,
            'result'         => $result,
            'result_type'    => gettype($result),
            'upload_success' => $result !== false,
        ]);

        if ($result === false) {
            Log::error('[avatar-upload] FALHA NO UPLOAD S3 — Storage::put() retornou false', [
                'path'      => $path,
                'disk'      => 's3',
                'bucket'    => config('filesystems.disks.s3.bucket'),
                'region'    => config('filesystems.disks.s3.region'),
                'endpoint'  => config('filesystems.disks.s3.endpoint'),
            ]);
        }

        // Verificar se o arquivo realmente existe no S3 após o upload
        $existsAfterUpload = Storage::disk('s3')->exists($path);
        Log::warning('[avatar-upload] Verificação pós-upload: arquivo existe no S3?', [
            'path'   => $path,
            'exists' => $existsAfterUpload,
        ]);

        return $path;
    }
}
