<?php

namespace App\Services;

use Illuminate\Http\UploadedFile;
use Illuminate\Support\Str;

/**
 * Guarda avatares en {@see public_path()} (sin symlink storage) para hosting compartido.
 */
class UserPublicAvatarService
{
    private const RELATIVE_DIR = 'uploads/avatars';

    public function store(UploadedFile $file): string
    {
        $dir = public_path(self::RELATIVE_DIR);
        if (! is_dir($dir)) {
            mkdir($dir, 0755, true);
        }

        $ext = strtolower((string) ($file->getClientOriginalExtension() ?: $file->guessExtension() ?: 'jpg'));
        if (! in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp'], true)) {
            $ext = 'jpg';
        }

        $basename = Str::uuid()->toString().'.'.$ext;
        $file->move($dir, $basename);

        return self::RELATIVE_DIR.'/'.$basename;
    }

    public function delete(?string $relativePath): void
    {
        if ($relativePath === null || $relativePath === '') {
            return;
        }

        $relativePath = str_replace('\\', '/', $relativePath);
        if (! str_starts_with($relativePath, self::RELATIVE_DIR.'/')) {
            return;
        }

        $full = public_path($relativePath);
        $realPublic = realpath(public_path());
        if ($realPublic === false || ! is_file($full)) {
            return;
        }

        $realFile = realpath($full);
        if ($realFile !== false && str_starts_with($realFile, $realPublic.DIRECTORY_SEPARATOR)) {
            @unlink($realFile);
        }
    }
}
