package com.lesingle.edu.controller;

import com.lesingle.edu.common.annotation.Log;
import com.lesingle.edu.common.enums.LogModule;
import com.lesingle.edu.common.enums.LogOperationType;
import com.lesingle.edu.common.response.Result;
import com.lesingle.edu.common.util.OssUtils;
import com.lesingle.edu.dto.response.OssTokenVo;
import com.lesingle.edu.service.FileStorageService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传控制器
 */
@RestController
@RequestMapping("/api/v1/files")
@RequiredArgsConstructor
@Tag(name = "文件上传")
public class FileUploadController {

    private final FileStorageService fileStorageService;
    private final OssUtils ossUtils;

    /**
     * 获取阿里云 OSS 直传 Token
     * <p>
     * 用于前端直传文件到 OSS，无需经过后端中转
     * </p>
     *
     * @param fileName 原始文件名（如：图片.jpg）
     * @param dir      目录前缀（可选，如：avatar, course/cover）
     * @return OSS 直传 Token VO
     */
    @GetMapping("/oss/token")
    @Operation(summary = "获取阿里云 OSS 直传 Token")
    public Result<OssTokenVo> getOssToken(
            @RequestParam("fileName") String fileName,
            @RequestParam(value = "dir", required = false) String dir) {

        OssTokenVo token = ossUtils.generatePostObjectToken(fileName, dir);
        return Result.success(token);
    }

    @PostMapping("/upload")
    @Operation(summary = "上传文件")
    @Log(module = LogModule.FILE, type = LogOperationType.CREATE, description = "上传文件")
    public Result<Map<String, Object>> uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "type", defaultValue = "other") String type) {

        // 验证文件类型
        if (!fileStorageService.validateFileType(file, type)) {
            return Result.error(400, "不支持的文件类型");
        }

        // 验证文件大小
        if (!fileStorageService.validateFileSize(file, type)) {
            return Result.error(400, "文件大小超过限制");
        }

        try {
            String fileUrl = fileStorageService.saveFile(file, type);

            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("filePath", fileUrl);
            result.put("fileName", file.getOriginalFilename());
            result.put("fileSize", file.getSize());
            result.put("mimeType", file.getContentType());

            return Result.success(result);
        } catch (Exception e) {
            return Result.error(500, "文件上传失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除文件")
    @Log(module = LogModule.FILE, type = LogOperationType.DELETE, description = "删除文件")
    public Result<Map<String, Object>> deleteFile(@RequestBody Map<String, String> request) {
        String filePath = request.get("filePath");

        if (filePath == null || filePath.isEmpty()) {
            return Result.error(400, "文件路径不能为空");
        }

        boolean success = fileStorageService.deleteFile(filePath);

        Map<String, Object> result = new HashMap<>();
        result.put("success", success);
        result.put("message", success ? "文件删除成功" : "文件不存在或删除失败");

        return Result.success(result);
    }
}
