package top.imwork.window.silos.controller.oss;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.imwork.commons.core.enums.HttpStatusCodeEnum;
import top.imwork.commons.core.pojo.ApiResponse;
import top.imwork.commons.core.pojo.FileUploadRequest;
import top.imwork.commons.core.pojo.FileUploadResponse;
import top.imwork.commons.core.pojo.ResponseMsg;
import top.imwork.window.silos.service.oss.FileUploadServiceImpl;
import top.imwork.window.silos.utils.SecurityUtils;

import java.io.IOException;
import java.util.List;

/**
 * Copyright (C), 2015-2025
 * FileName: FilesUploadController
 * Author<作者姓名>:   stars
 * CreateTime<创建时间>:   2025/12/15 15:54
 * UpdateTime<修改时间>:   2025/12/15 15:54
 * Description〈功能简述〉: 文件上传控制器
 * History<历史描述>:
 * Since<版本号>: 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
public class FilesUploadController {
    @Autowired
    private FileUploadServiceImpl fileUploadService;

    @Value("${upload.allowed-extensions}")
    private List<String> allowedExtensions;

    @PostMapping("/upload")
    public ResponseEntity<ApiResponse<FileUploadResponse>> uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "fileName", required = false) String fileName,
            @RequestParam(value = "fileHash", required = false) String fileHash,
            HttpServletRequest request) {
        FileUploadResponse uploadResponse = null;
        try {
            log.info("收到文件上传请求: 文件名={}, 大小={}, 类型={}",
                    file.getOriginalFilename(),
                    file.getSize(),
                    file.getContentType());

            // 1. 基础校验
            if (file.isEmpty()) {
                return ResponseEntity.badRequest()
                        .body(ApiResponse.error("文件不能为空"));
            }

            // 2. 安全检查
            String securityCheck = SecurityUtils.checkFileSecurity(file);
            if (securityCheck != null) {
                log.warn("文件安全检查失败: {}", securityCheck);
                return ResponseEntity.badRequest()
                        .body(ApiResponse.error(securityCheck));
            }

            // 3. 上传文件
            uploadResponse = fileUploadService.uploadFile(file);

            log.info("文件上传成功: {}", uploadResponse.getFilePath());

            return ResponseEntity.ok(ApiResponse.success(uploadResponse));

        } catch (Exception e) {
            log.error("文件上传失败", e);
            /*return ResponseEntity.internalServerError()
                    .body(ApiResponse.error("文件上传失败: " + e.getMessage()));*/
            return ResponseEntity.ok(ApiResponse.success(uploadResponse));
        }
    }

    /**
     * 通用文件上传接口（支持单文件和双文件）
     * 使用JSON格式接收参数，文件通过Multipart上传
     */
    @PostMapping("/file/upload")
    public ResponseMsg uploadFiles(@Valid FileUploadRequest request){
        FileUploadResponse uploadResponse = null;
        if (request.getFile() != null || !request.getFile().isEmpty()) {
            // 2. 安全检查
            String securityCheck = SecurityUtils.checkFileSecurity(request.getFile());
            if (securityCheck != null) {
                log.warn("文件安全检查失败: {}", securityCheck);
                return ResponseMsg.buildResponse(HttpStatusCodeEnum.BAD_REQUEST.getCode(), securityCheck);
            }
            // 3. 上传文件
            uploadResponse = fileUploadService.upload(request);
            log.info("文件上传成功: {}", uploadResponse.getFilePath());
            return ResponseMsg.buildResponse(uploadResponse);
        } else if (!request.getFiles().isEmpty()) {
            uploadResponse = fileUploadService.upload(request);
            return ResponseMsg.buildResponse(uploadResponse);
        } else {
            // 1. 基础校验
            return ResponseMsg.buildResponse(HttpStatusCodeEnum.BAD_REQUEST.getCode(), "文件不能为空");
        }
    }
}