<?php

declare(strict_types=1);

namespace App\Support;

final class AvatarPath
{
    /**
     * Normalize an uploaded avatar URL or relative path to a stored path.
     */
    public static function normalize(?string $value): ?string
    {
        if ($value === null) {
            return null;
        }

        $value = trim($value);

        if ($value === '') {
            return null;
        }

        if (str_starts_with($value, 'http://') || str_starts_with($value, 'https://')) {
            $path = parse_url($value, PHP_URL_PATH);

            if (! is_string($path) || $path === '') {
                return $value;
            }

            $value = ltrim($path, '/');
        }

        $value = ltrim(str_replace('\\', '/', $value), '/');

        if (str_starts_with($value, 'storage/')) {
            $value = substr($value, strlen('storage/'));
        }

        return $value;
    }
}
