<?php
declare(strict_types=1);
function createShortCode(PDO $pdo,string $url): string {
    if (!filter_var($url,FILTER_VALIDATE_URL) || !in_array(strtolower((string)parse_url($url,PHP_URL_SCHEME)),['http','https'],true)) {
        throw new InvalidArgumentException('Only valid HTTP(S) URLs are accepted.');
    }
    for ($i=0;$i<5;$i++) {
        $code=rtrim(strtr(base64_encode(random_bytes(6)),'+/','-_'),'=');
        try {
            $s=$pdo->prepare('INSERT INTO short_urls(code,target_url,created_at) VALUES(:code,:url,NOW())');
            $s->execute(['code'=>$code,'url'=>$url]); return $code;
        } catch (PDOException $e) { if ($e->getCode()!=='23000') throw $e; }
    }
    throw new RuntimeException('Could not create unique code.');
}
