<?php

declare(strict_types=1);

namespace App\Support;

use Illuminate\Support\Facades\Storage;

class FileUrl
{
    public const PRIVATE_PREFIX = 'private/';

    public const DISK = 'user_uploads';

    public static function isPrivate(?string $path): bool
    {
        return is_string($path) && str_starts_with($path, self::PRIVATE_PREFIX);
    }

    public static function toStoragePath(string $path): string
    {
        return self::isPrivate($path)
            ? substr($path, strlen(self::PRIVATE_PREFIX))
            : $path;
    }

    public static function toStoredPath(string $storagePath): string
    {
        return self::PRIVATE_PREFIX.$storagePath;
    }

    public static function url(?string $path): ?string
    {
        if ($path === null || $path === '') {
            return null;
        }

        if (str_starts_with($path, 'http')) {
            return $path;
        }

        if (self::isPrivate($path)) {
            $storagePath = self::toStoragePath($path);

            if (! Storage::disk(self::DISK)->exists($storagePath)) {
                return null;
            }

            return self::normalizeUrl(
                Storage::disk(self::DISK)->url($storagePath)
            );
        }

        return self::normalizeUrl(url($path));
    }

    public static function normalizeUrl(string $url): string
    {
        return preg_replace('#(?<!:)/{2,}#', '/', $url) ?? $url;
    }

    /**
     * @param  array<int, mixed>|null  $paths
     * @return array<int, string>|null
     */
    public static function urls(?array $paths): ?array
    {
        if ($paths === null) {
            return null;
        }

        return array_values(array_filter(array_map(
            fn ($path): ?string => is_string($path) ? self::url($path) : null,
            $paths
        )));
    }
}
