<?php
declare(strict_types=1);

namespace Opentalent\OtCore\Utility;

/**
 * Building url utilities
 */
class UrlUtils
{
    /**
     * Concatenate a base url and a path
     *
     * @param string $base The base url
     * @param array<string> $tails La suite de l'URL sous forme de tableau
     * @return string
     */
    public static function concatPath(string $base, array $tails): string
    {
        $url = $base;
        foreach ($tails as $tail){
            $url = rtrim($url, '/') . '/' . ltrim(strval($tail), '/');
        }
        return $url;
    }

    /**
     * Concatenate an url and a list of parameters
     *
     * @param string $url
     * @param list<string | int> $parameters
     * @return string
     */
    public static function concatParameters(string $url, array $parameters = []): string
    {
        if (!$parameters) { return $url; }
        $url = rtrim($url, '?&/');
        $query = implode(
            '&',
            array_map(
                static function ($k, $v = '') {
                    $q = urlencode((string)$k);
                    if ((string)$v) {
                        $q .= '=' . urlencode((string)$v);
                    }
                    return $q;
                },
                array_keys($parameters),
                array_values($parameters)
            )
        );
        return $url . (str_contains($url, '?') ?  '&' : '?') . $query;
    }

    /**
     * Prepend the 'https://' part if neither 'http://' of 'https://' is present, else: does nothing
     *
     * @param string $url
     * @return string
     */
    public static function prependHttps(string $url): string
    {
        if (!preg_match('/^https?:\/\/.*/', $url)) {
            $url = 'https://' . $url;
        }
        return $url;
    }

    /**
     * Build an url
     *
     * @param string $url The base url
     * @param array<string> $tails la suite de l'url sous forme de tableau
     * @param list<string> $parameters A list of parameters (can be an empty array)
     * @param bool $preprendHttps Should the 'https://' be prepended if missing
     * @return string
     */
    public static function concat(string $url, array $tails, array $parameters, bool $preprendHttps = false): string
    {
        $url = self::concatParameters(self::concatPath($url, $tails), $parameters);
        if ($preprendHttps) {
            $url = self::prependHttps($url);
        }
        return $url;
    }

    public static function join(string ...$url): string
    {
        return self::concatPath($url[0], array_splice($url, 1));
    }

    public static function normalizePath(string $path): string
    {
        return '/' . trim($path, '/');
    }

    public static function normalizeDomain(string $domain): string
    {
        return preg_replace('/https?:\/\/([\w.]+)(?:\/.*)?/', '$1', $domain);
    }
}
