package cn.nianxx.thhotel.platform.documentconversion.control;

import cn.nianxx.thhotel.platform.documentconversion.common.result.DocumentConversionErrorResponse;
import cn.nianxx.thhotel.platform.documentconversion.service.DocumentConversionException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

/**
 * 文件转换接口异常转换。只返回安全错误摘要，不暴露 Excel 内容、PDF 内容、临时路径或 Secret。
 */
@RestControllerAdvice(assignableTypes = DocumentConversionController.class)
public class DocumentConversionControllerAdvice {

    /**
     * 转换文件转换业务异常。
     */
    @ExceptionHandler(DocumentConversionException.class)
    public ResponseEntity<DocumentConversionErrorResponse> handleDocumentConversionException(
            DocumentConversionException exception) {
        return ResponseEntity.status(exception.getStatus())
                .body(new DocumentConversionErrorResponse(exception.getErrorCode(), exception.getMessage()));
    }

    /**
     * 转换缺少 multipart 文件或必填参数的异常。
     */
    @ExceptionHandler({MissingServletRequestPartException.class, MissingServletRequestParameterException.class})
    public ResponseEntity<DocumentConversionErrorResponse> handleMissingRequestPart(Exception exception) {
        return ResponseEntity.badRequest()
                .body(new DocumentConversionErrorResponse(
                        "DOCUMENT_CONVERSION_FILE_REQUIRED",
                        "请上传 Excel 文件。"));
    }

    /**
     * 转换 Spring multipart 框架层上传大小超限异常。
     */
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ResponseEntity<DocumentConversionErrorResponse> handleMaxUploadSizeExceeded(
            MaxUploadSizeExceededException exception) {
        return ResponseEntity.status(HttpStatus.PAYLOAD_TOO_LARGE)
                .body(new DocumentConversionErrorResponse(
                        "DOCUMENT_CONVERSION_FILE_TOO_LARGE",
                        "上传的 Excel 文件超过大小限制。"));
    }
}
