package com.lesingle.creation.controller;

import com.lesingle.creation.common.core.Result;
import com.lesingle.creation.common.exception.BusinessException;
import com.lesingle.creation.common.security.UserPrincipal;
import com.lesingle.creation.common.util.OssUtil;
import com.lesingle.creation.vo.upload.UploadResponseVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传控制器
 */
@Tag(name = "文件上传", description = "文件上传、删除等接口")
@Slf4j
@RestController
@RequestMapping("/api/upload")
@RequiredArgsConstructor
public class UploadController {

    private final OssUtil ossUtil;

    /**
     * 上传文件
     */
    @Operation(summary = "上传文件")
    @PostMapping
    public Result<UploadResponseVO> uploadFile(
            @RequestParam("file") MultipartFile file,
            @AuthenticationPrincipal UserPrincipal userPrincipal) {
        try {
            if (file == null || file.isEmpty()) {
                throw new BusinessException("请选择要上传的文件");
            }

            // 调用 OssUtil 上传文件
            String fileUrl = ossUtil.upload(file);

            // 构建响应
            UploadResponseVO response = new UploadResponseVO();
            response.setUrl(fileUrl);
            response.setFileName(file.getOriginalFilename());
            response.setSize(file.getSize());

            log.info("文件上传成功，文件名={}, 大小={}", file.getOriginalFilename(), file.getSize());

            return Result.success(response);

        } catch (IOException e) {
            log.error("文件上传失败", e);
            throw new BusinessException("文件上传失败：" + e.getMessage());
        }
    }

    /**
     * 删除文件
     */
    @Operation(summary = "删除文件")
    @DeleteMapping
    public Result<Void> deleteFile(@RequestParam("url") String fileUrl) {
        try {
            ossUtil.delete(fileUrl);
            return Result.success(null);
        } catch (Exception e) {
            log.error("文件删除失败", e);
            throw new BusinessException("文件删除失败：" + e.getMessage());
        }
    }
}
