package com.usky.vpp.web.advice;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.usky.vpp.controller.un.UnDnController;
import com.usky.vpp.crypto.VppUnCryptoService;
import com.usky.vpp.crypto.VppUnSmCryptoUtil;
import com.usky.vpp.util.VppUnCipherPayloadHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * DN 响应 UN 被动调用时，可选国密加密响应体
 */
@ControllerAdvice(assignableTypes = UnDnController.class)
public class VppUnDnCryptoResponseAdvice implements ResponseBodyAdvice<Object> {

    @Autowired
    private VppUnCryptoService cryptoService;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        if (returnType.getMethod() != null && "tokenRequest".equals(returnType.getMethod().getName())) {
            return false;
        }
        return cryptoService.isAnyActive();
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        if (body == null) {
            return null;
        }
        try {
            String plainJson = body instanceof String ? (String) body : objectMapper.writeValueAsString(body);
            VppUnSmCryptoUtil.EncryptedPayload payload = cryptoService.prepareOutbound(plainJson);
            response.getHeaders().set("X-Sign", payload.getSignBase64());
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return VppUnCipherPayloadHelper.wrapCipherPayload(payload.getCipherBase64(), objectMapper);
        } catch (com.usky.common.core.exception.BusinessException ex) {
            throw ex;
        } catch (Exception ex) {
            throw new com.usky.common.core.exception.BusinessException("DN 响应加密失败: " + ex.getMessage());
        }
    }
}
