package com.tzld.piaoquan.growth.common.utils;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

public class ImageUrlValidator {

    // 常见图片类型列表
    private static final List<String> IMAGE_CONTENT_TYPES = Arrays.asList(
            "image/jpeg", "image/png", "image/gif", "image/bmp",
            "image/webp", "image/svg+xml", "image/tiff"
    );

    // 连接超时时间（毫秒）
    private static final int CONNECTION_TIMEOUT = 5000;
    // 读取超时时间（毫秒）
    private static final int READ_TIMEOUT = 5000;

    /**
     * 验证图片URL是否有效
     * @param imageUrl 图片URL
     * @return 如果URL有效且指向图片返回true，否则返回false
     */
    public static boolean isValidImageUrl(String imageUrl) {
        if (imageUrl == null || imageUrl.trim().isEmpty()) {
            return false;
        }

        HttpURLConnection connection = null;
        try {
            URL url = new URL(imageUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(CONNECTION_TIMEOUT);
            connection.setReadTimeout(READ_TIMEOUT);
            connection.setRequestMethod("HEAD"); // 使用HEAD请求减少数据传输

            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                return false;
            }

            String contentType = connection.getContentType();
            return contentType != null &&
                    IMAGE_CONTENT_TYPES.stream().anyMatch(contentType::contains);

        } catch (IOException e) {
            return false;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
}
