package cn.sikey.mcdisk.util;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author: nelson
 * @Date: 2025/6/26
 * @Description: url拼接
 */
public class UrlBuilderUtil {
    private final String baseUrl;
    private final Map<String, String> params = new LinkedHashMap<>();

    public UrlBuilderUtil(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    public UrlBuilderUtil addParam(String key, String value) {
        params.put(key, value);
        return this;
    }

    public String build() {
        StringBuilder url = new StringBuilder(baseUrl);
        if (!params.isEmpty()) {
            url.append(baseUrl.contains("?") ? "&" : "?");
            params.forEach((k, v) -> {
                url.append(encode(k)).append("=").append(encode(v)).append("&");
            });
            url.deleteCharAt(url.length() - 1);
        }
        return url.toString();
    }

    private String encode(String str) {
        return URLEncoder.encode(str, StandardCharsets.UTF_8);
    }
}
