<%@ page language="java" contentType="application/json; charset=UTF-8" pageEncoding="UTF-8" trimDirectiveWhitespaces="true" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.LinkedHashMap" %>
<%@ page import="java.net.HttpURLConnection" %>
<%@ page import="java.net.URL" %>
<%@ page import="java.io.InputStream" %>
<%@ page import="java.io.OutputStream" %>
<%@ page import="java.io.ByteArrayOutputStream" %>
<%
    Map<String, String> allowedTargets = new LinkedHashMap<String, String>();
    allowedTargets.put("wfinfo", "/api/workflow/createreq/wfinfo");
    allowedTargets.put("loadForm", "/api/workflow/reqform/loadForm");
    allowedTargets.put("loadFormCreate", "/api/workflow/reqform/loadForm");
    allowedTargets.put("loadFormRead", "/api/workflow/reqform/loadForm");
    allowedTargets.put("detailData", "/api/workflow/reqform/detailData");
    allowedTargets.put("doCreateRequest", "/api/workflow/paService/doCreateRequest");

    Map<String, String> allowedMethods = new LinkedHashMap<String, String>();
    allowedMethods.put("wfinfo", "GET");
    allowedMethods.put("loadForm", "POST");
    allowedMethods.put("loadFormCreate", "POST");
    allowedMethods.put("loadFormRead", "POST");
    allowedMethods.put("detailData", "POST");
    allowedMethods.put("doCreateRequest", "POST");

    String operation = request.getHeader("X-BoltFusion-E9-Operation");
    if ((operation == null || operation.length() == 0) && "GET".equalsIgnoreCase(request.getMethod())) {
        operation = request.getParameter("bfOperation");
    }
    String target = allowedTargets.get(operation);
    String expectedMethod = allowedMethods.get(operation);
    if (target == null || expectedMethod == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.clear();
        out.print("{\"ok\":false,\"error\":\"unsupported_operation\"}");
        return;
    }
    if (!expectedMethod.equalsIgnoreCase(request.getMethod())) {
        response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        response.setHeader("Allow", expectedMethod);
        out.clear();
        out.print("{\"ok\":false,\"error\":\"method_not_allowed\"}");
        return;
    }

    Object user = session.getAttribute("weaver_user@bean");
    if (user == null) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        out.clear();
        out.print("{\"ok\":false,\"error\":\"mobiletoken_session_missing\"}");
        return;
    }

    // 部分 Ecology 版本的 MobileToken SSO 会把这两个值写成 Integer，
    // 而后续 SessionFilter 直接按 String 读取。统一为 String 后再访问 E9 API。
    Object openType = session.getAttribute("@openType");
    if (openType != null && !(openType instanceof String)) {
        session.setAttribute("@openType", String.valueOf(openType));
    }
    Object userLoginFrom = session.getAttribute("userLoginFrom");
    if (userLoginFrom != null && !(userLoginFrom instanceof String)) {
        session.setAttribute("userLoginFrom", String.valueOf(userLoginFrom));
    }

    String rawQuery = request.getQueryString();
    StringBuilder forwardedQuery = new StringBuilder();
    if (rawQuery != null && rawQuery.length() > 0) {
        String[] parts = rawQuery.split("&");
        for (String part : parts) {
            if (part.equals("bfOperation") || part.startsWith("bfOperation=")) {
                continue;
            }
            if (forwardedQuery.length() > 0) {
                forwardedQuery.append('&');
            }
            forwardedQuery.append(part);
        }
    }

    String internalUrl = "http://127.0.0.1:" + request.getLocalPort() + target;
    if (forwardedQuery.length() > 0) {
        internalUrl += "?" + forwardedQuery.toString();
    }

    byte[] requestBytes = new byte[0];
    if (!"GET".equalsIgnoreCase(request.getMethod())) {
        InputStream requestBody = request.getInputStream();
        ByteArrayOutputStream bufferedRequest = new ByteArrayOutputStream();
        byte[] buffer = new byte[8192];
        int count;
        while ((count = requestBody.read(buffer)) != -1) {
            bufferedRequest.write(buffer, 0, count);
        }
        requestBytes = bufferedRequest.toByteArray();
    }

    HttpURLConnection connection = (HttpURLConnection) new URL(internalUrl).openConnection();
    connection.setRequestMethod(expectedMethod);
    connection.setConnectTimeout(15000);
    connection.setReadTimeout(120000);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestProperty("Accept", "application/json, text/plain, */*");
    connection.setRequestProperty("Accept-Encoding", "identity");
    connection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
    connection.setRequestProperty("User-Agent", "BoltFusion-E9-Mobile-API-Bridge/1.0");
    connection.setRequestProperty("Cookie", "JSESSIONID=" + session.getId());

    String contentType = request.getContentType();
    if (contentType != null && contentType.length() > 0) {
        connection.setRequestProperty("Content-Type", contentType);
    }
    if (!"GET".equalsIgnoreCase(expectedMethod)) {
        connection.setDoOutput(true);
        connection.setFixedLengthStreamingMode(requestBytes.length);
        OutputStream upstreamBody = connection.getOutputStream();
        upstreamBody.write(requestBytes);
        upstreamBody.flush();
        upstreamBody.close();
    }

    int upstreamStatus = connection.getResponseCode();
    InputStream upstreamStream =
            upstreamStatus >= 400 ? connection.getErrorStream() : connection.getInputStream();
    ByteArrayOutputStream upstreamBytes = new ByteArrayOutputStream();
    if (upstreamStream != null) {
        byte[] buffer = new byte[8192];
        int count;
        while ((count = upstreamStream.read(buffer)) != -1) {
            upstreamBytes.write(buffer, 0, count);
        }
        upstreamStream.close();
    }

    response.setStatus(upstreamStatus);
    String upstreamContentType = connection.getContentType();
    response.setContentType(
            upstreamContentType == null || upstreamContentType.length() == 0
                    ? "application/json; charset=UTF-8"
                    : upstreamContentType
    );
    response.setHeader("Cache-Control", "no-store");
    response.setHeader("X-BoltFusion-E9-Mobile-Bridge", "session-proxy");
    response.setHeader("X-BoltFusion-E9-Mobile-Bridge-Operation", operation);
    out.clear();
    out.print(new String(upstreamBytes.toByteArray(), "UTF-8"));
    connection.disconnect();
%>
