package com.gcsc.connection.gateway.controller;

import com.gcsc.connection.common.exception.BusinessException;
import com.gcsc.connection.gateway.service.GatewayService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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.RestController;

/**
 * API Gateway 프록시 엔드포인트
 */
@RestController
@RequestMapping("/gateway")
@RequiredArgsConstructor
@Slf4j
public class GatewayController {

    private final GatewayService gatewayService;

    /**
     * 모든 HTTP 메서드에 대한 프록시 요청 처리
     */
    @RequestMapping(
        value = "/{serviceCode}/**",
        method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT,
                  RequestMethod.DELETE, RequestMethod.PATCH}
    )
    public ResponseEntity<byte[]> proxy(@PathVariable String serviceCode,
                                        HttpServletRequest request) {
        try {
            String remainingPath = extractRemainingPath(serviceCode, request);
            return gatewayService.proxyRequest(serviceCode, remainingPath, request);
        } catch (BusinessException e) {
            return buildErrorResponse(e.getErrorCode().getStatus(), e.getErrorCode().getCode(), e.getErrorCode().getMessage());
        }
    }

    /**
     * /gateway/{serviceCode}/ 이후의 경로 추출
     */
    private String extractRemainingPath(String serviceCode, HttpServletRequest request) {
        String fullPath = request.getRequestURI();
        String contextPath = request.getContextPath();
        String prefix = contextPath + "/gateway/" + serviceCode;
        String remainingPath = fullPath.substring(prefix.length());

        if (remainingPath.isEmpty()) {
            remainingPath = "/";
        }

        return remainingPath;
    }

    /**
     * Gateway 소비자용 JSON 에러 응답 생성
     */
    private ResponseEntity<byte[]> buildErrorResponse(int status, String code, String message) {
        String json = "{\"success\":false,\"code\":\"" + escapeJson(code) + "\",\"message\":\"" + escapeJson(message) + "\"}";
        return ResponseEntity.status(status)
            .contentType(MediaType.APPLICATION_JSON)
            .body(json.getBytes());
    }

    /**
     * JSON 문자열 이스케이프 처리
     */
    private String escapeJson(String value) {
        if (value == null) {
            return "";
        }
        return value.replace("\\", "\\\\")
            .replace("\"", "\\\"")
            .replace("\n", "\\n")
            .replace("\r", "\\r")
            .replace("\t", "\\t");
    }
}
