package com.ycwl.basic.controller.proxy;

import com.ycwl.basic.annotation.IgnoreToken;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

@Deprecated
@RestController
public class ProxyController {
    @IgnoreToken
    @RequestMapping(value = "/proxy", method = RequestMethod.GET)
    public void proxy(@RequestParam(value = "url") String url,
                      HttpServletRequest request,
                      HttpServletResponse response) throws IOException {
        if (!url.startsWith("http://") && !url.startsWith("https://")) {
            url = "http://" + url; // 或根据业务逻辑选择默认协议
        }

        // 新增User-Agent检测逻辑
        String userAgent = request.getHeader("User-Agent");
        if (userAgent != null && userAgent.contains("Lavf/")) {
            response.sendRedirect(url);
            return;
        }
        // 创建HTTP连接
        URL urlObj = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();

        // 设置请求方法和请求头
        connection.setRequestMethod("GET");
        for (Enumeration<String> headers = request.getHeaderNames(); headers.hasMoreElements();) {
            String headerName = headers.nextElement();
            connection.addRequestProperty(headerName, request.getHeader(headerName));
        }

        // 处理响应
        int responseCode = connection.getResponseCode();
        response.setStatus(responseCode);

        // 转发响应头
        Map<String, List<String>> headerFields = connection.getHeaderFields();
        for (Map.Entry<String, List<String>> entry : headerFields.entrySet()) {
            if (entry.getKey() != null) {
                for (String value : entry.getValue()) {
                    response.addHeader(entry.getKey(), value);
                }
            }
        }

        // 流式传输响应体
        try (InputStream inputStream = connection.getInputStream();
             OutputStream outputStream = response.getOutputStream()) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            return;
        }
    }
}
