package com.huangzj.protoplugin.vcs;

import java.net.HttpURLConnection;
import java.net.URL;
import org.jetbrains.annotations.Nullable;

/** 通过 HTTP 响应头 Date 获取参考时间（UTC），用于与本机 {@link System#currentTimeMillis()} 对比。 */
public final class TimeSkewChecker {

    private static final int CONNECT_MS = 5_000;
    private static final int READ_MS = 5_000;

    /** 国内可访问的站点，依次尝试 HEAD。 */
    private static final String[] HEAD_URLS = {
        "https://www.aliyun.com",
        "https://www.qq.com",
        "https://www.baidu.com",
    };

    private TimeSkewChecker() {}

    /**
     * @return 服务器认为的当前纪元毫秒；全部失败时返回 {@code null}（调用方宜放行提交）。
     */
    @Nullable
    public static Long fetchReferenceEpochMillis() {
        for (String spec : HEAD_URLS) {
            Long t = tryHeadDate(spec);
            if (t != null && t > 0) {
                return t;
            }
        }
        return null;
    }

    @Nullable
    private static Long tryHeadDate(String spec) {
        HttpURLConnection c = null;
        try {
            URL url = new URL(spec);
            c = (HttpURLConnection) url.openConnection();
            c.setRequestMethod("HEAD");
            c.setInstanceFollowRedirects(true);
            c.setConnectTimeout(CONNECT_MS);
            c.setReadTimeout(READ_MS);
            c.setRequestProperty("User-Agent", "ProtoPlugin-TimeCheck/1.0");
            c.connect();
            long d = c.getDate();
            return d > 0 ? d : null;
        } catch (Exception ignored) {
            return null;
        } finally {
            if (c != null) {
                c.disconnect();
            }
        }
    }
}
