<?php

declare(strict_types=1);

namespace app\common\service;

/**
 * 按号码类型拼接各平台加好友链接
 */
class SplitFriendUrlBuilder
{
    /**
     * 构建跳转 URL；无法构建时返回空字符串
     *
     * @param string $replyText WhatsApp / Telegram 预填消息文案（内部 rawurlencode）
     */
    public static function build(
        string $numberType,
        string $number,
        string $numberTypeCustom = '',
        string $replyText = ''
    ): string {
        $number = trim($number);
        if ($number === '') {
            return '';
        }

        switch ($numberType) {
            case 'whatsapp':
                return self::buildWhatsApp($number, $replyText);
            case 'telegram':
                return self::buildTelegram($number, $replyText);
            case 'line':
                return self::buildLine($number);
            case 'custom':
                return self::buildCustom($number, $numberTypeCustom);
            default:
                return '';
        }
    }

    /**
     * WhatsApp：https://api.whatsapp.com/send?phone= 仅数字，可选 &text= 预填消息
     */
    private static function buildWhatsApp(string $number, string $replyText = ''): string
    {
        $digits = preg_replace('/\D+/', '', $number) ?? '';
        if ($digits === '') {
            return '';
        }

        $url = 'https://api.whatsapp.com/send?phone=' . $digits;
        $replyText = trim($replyText);
        if ($replyText !== '') {
            $url .= '&text=' . rawurlencode($replyText);
        }

        return $url;
    }

    /**
     * Telegram：https://t.me/+ 号码（去掉前导 +），可选 ?text= 预填消息（须 URL 编码）
     */
    private static function buildTelegram(string $number, string $replyText = ''): string
    {
        $id = ltrim($number, '+');
        if ($id === '') {
            return '';
        }

        $url = 'https://t.me/+' . $id;
        $replyText = trim($replyText);
        if ($replyText !== '') {
            $url .= '?text=' . rawurlencode($replyText);
        }

        return $url;
    }

    /**
     * Line：https://line.me/ti/p/~ 拼接号码
     */
    private static function buildLine(string $number): string
    {
        return 'https://line.me/ti/p/~' . $number;
    }

    /**
     * 自定义：号码字段即为完整链接（仅允许 http/https）
     */
    private static function buildCustom(string $number, string $numberTypeCustom): string
    {
        $url = trim($number);
        if ($url === '' && trim($numberTypeCustom) !== '') {
            $url = trim($numberTypeCustom);
        }
        if ($url === '') {
            return '';
        }
        if (!filter_var($url, FILTER_VALIDATE_URL)) {
            return '';
        }
        $scheme = strtolower((string) parse_url($url, PHP_URL_SCHEME));
        if (!in_array($scheme, ['http', 'https'], true)) {
            return '';
        }

        return $url;
    }
}
