<?php

namespace App\Services;

use App\Models\Media;
use App\Traits\RemoveArchiveS3;
use App\Traits\UploadsFile;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Log;

class MediaService
{
    use RemoveArchiveS3, UploadsFile;

    public function getAll(): Collection
    {
        return Media::query()
            ->with(['user'])
            ->orderBy('created_at', 'desc')
            ->get();
    }

    public function findById(int $id): ?Media
    {
        return Media::with(['user'])->find($id);
    }

    public function create(array $data): Media
    {
        return Media::create($data);
    }

    public function update(int $id, array $data): ?Media
    {
        $model = $this->findById($id);

        if (! $model) {
            return null;
        }

        $model->update($data);

        return $model->fresh(['user']);
    }

    public function delete(int $id): bool
    {
        $model = $this->findById($id);

        if (! $model) {
            return false;
        }

        return $model->delete();
    }

    //

    public function createFromFile(UploadedFile $file, string $folder, string $source, int $sourceId, ?string $filename = null): Media
    {
        Log::warning('[avatar-upload] MediaService::createFromFile — iniciando upload para S3', [
            'folder'             => $folder,
            'source'             => $source,
            'source_id'          => $sourceId,
            'file_original_name' => $file->getClientOriginalName(),
            'file_size'          => $file->getSize(),
            'file_mime'          => $file->getMimeType(),
            'file_extension'     => $file->getClientOriginalExtension(),
            'file_is_valid'      => $file->isValid(),
        ]);

        $path = $this->uploadFile($file, $folder, $filename);

        Log::warning('[avatar-upload] MediaService::createFromFile — upload concluído, criando registro Media', [
            'path_retornado' => $path,
            'source'         => $source,
            'source_id'      => $sourceId,
        ]);

        $media = Media::create([
            'source'    => $source,
            'source_id' => $sourceId,
            'name'      => $file->getClientOriginalName(),
            'path'      => $path,
        ]);

        Log::warning('[avatar-upload] MediaService::createFromFile — Media criado no banco', [
            'media_id'   => $media->id,
            'media_path' => $media->path,
            'media_url'  => $media->url ?? null,
        ]);

        return $media;
    }

    public function replaceFile(UploadedFile $newFile, string $folder, string $source, int $sourceId, ?Media $old = null, ?string $filename = null): Media
    {
        Log::warning('[avatar-upload] MediaService::replaceFile iniciado', [
            'folder'        => $folder,
            'source'        => $source,
            'source_id'     => $sourceId,
            'has_old_media' => $old !== null,
            'old_media_id'  => $old?->id,
            'old_path'      => $old?->path,
        ]);

        if ($old) {
            Log::warning('[avatar-upload] Removendo arquivo antigo do S3', ['old_path' => $old->path]);

            $this->removeArchiveByPath($old->path);

            $old->delete();

            Log::warning('[avatar-upload] Arquivo antigo removido do S3 e Media deletado do banco');
        }

        return $this->createFromFile($newFile, $folder, $source, $sourceId, $filename);
    }
}
