package com.dora.controller;

import com.dora.annotation.RequireAdminOrStaff;
import com.dora.common.Result;
import com.dora.dto.AdminOssUploadRequest;
import com.dora.dto.AdminOssUploadResponse;
import com.dora.service.AdminOssService;
import com.dora.util.AdminSecurityUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.Map;

/**
 * 管理端文件上传控制器（兼容旧版API路径）
 * 提供与 /admin/oss/* 相同的功能，但使用 /admin/upload/* 路径以保持向后兼容
 */
@RestController
@RequestMapping("/admin/upload")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "管理端文件上传(兼容)", description = "管理端文件上传兼容接口，与/admin/oss/*功能相同")
@RequireAdminOrStaff
public class AdminUploadController {

    private final AdminOssService adminOssService;

    @PostMapping("/cover")
    @Operation(summary = "生成文件上传签名(兼容)", description = "生成OSS POST签名，兼容旧版API路径")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "成功生成POST签名",
                    content = @Content(schema = @Schema(implementation = AdminOssUploadResponse.class))),
            @ApiResponse(responseCode = "400", description = "请求参数错误"),
            @ApiResponse(responseCode = "401", description = "未授权访问"),
            @ApiResponse(responseCode = "403", description = "权限不足"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<AdminOssUploadResponse> uploadCover(
            @Valid @RequestBody AdminOssUploadRequest request) {
        try {
            // 获取当前管理员ID
            String adminId = AdminSecurityUtil.getCurrentAdminId().toString();
            
            log.info("管理员 {} 通过兼容接口请求生成OSS上传签名: {}", adminId, request.getFileName());
            
            // 如果没有指定目录，默认使用 'covers' 目录
            if (request.getDirectory() == null || request.getDirectory().isEmpty()) {
                request.setDirectory("covers");
            }
            
            Map<String, Object> result = adminOssService.generateAdminPostSignature(request, adminId);
            AdminOssUploadResponse response = AdminOssUploadResponse.fromMap(result);
            
            return Result.success(response, "文件上传签名生成成功");
        } catch (IllegalArgumentException e) {
            log.warn("管理端文件上传参数错误: {}", e.getMessage());
            return Result.error(400, e.getMessage());
        } catch (Exception e) {
            log.error("管理端文件上传签名生成失败: {}", e.getMessage(), e);
            return Result.error(500, "生成上传签名失败: " + e.getMessage());
        }
    }

    @PostMapping("/signature")
    @Operation(summary = "生成通用上传签名(兼容)", description = "生成OSS POST签名，通用上传接口")
    public Result<AdminOssUploadResponse> uploadSignature(
            @Valid @RequestBody AdminOssUploadRequest request) {
        try {
            String adminId = AdminSecurityUtil.getCurrentAdminId().toString();
            
            log.info("管理员 {} 通过兼容接口请求生成通用上传签名: {}", adminId, request.getFileName());
            
            // 如果没有指定目录，默认使用 'uploads' 目录
            if (request.getDirectory() == null || request.getDirectory().isEmpty()) {
                request.setDirectory("uploads");
            }
            
            Map<String, Object> result = adminOssService.generateAdminPostSignature(request, adminId);
            AdminOssUploadResponse response = AdminOssUploadResponse.fromMap(result);
            
            return Result.success(response, "上传签名生成成功");
        } catch (IllegalArgumentException e) {
            log.warn("管理端上传参数错误: {}", e.getMessage());
            return Result.error(400, e.getMessage());
        } catch (Exception e) {
            log.error("管理端上传签名生成失败: {}", e.getMessage(), e);
            return Result.error(500, "生成上传签名失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/file")
    @Operation(summary = "删除文件(兼容)", description = "删除指定的OSS文件")
    public Result<String> deleteFile(
            @Parameter(description = "对象键", required = true) @RequestParam String objectKey) {
        try {
            String adminId = AdminSecurityUtil.getCurrentAdminId().toString();
            
            log.info("管理员 {} 通过兼容接口请求删除文件: {}", adminId, objectKey);
            
            boolean success = adminOssService.deleteAdminFile(objectKey, adminId);
            if (success) {
                return Result.success("文件删除成功");
            } else {
                return Result.error(400, "文件删除失败");
            }
        } catch (Exception e) {
            log.error("管理端删除文件失败: {}", e.getMessage(), e);
            return Result.error(500, "删除文件失败: " + e.getMessage());
        }
    }

    @GetMapping("/config")
    @Operation(summary = "获取上传配置(兼容)", description = "获取管理端文件上传的配置信息")
    public Result<Map<String, Object>> getUploadConfig() {
        try {
            Map<String, Object> config = Map.of(
                "maxFileSize", 500 * 1024 * 1024L,
                "maxFileSizeMB", 500,
                "supportedFormats", new String[]{
                    "图片: jpg, jpeg, png, gif, bmp, webp, svg, ico, tiff",
                    "文档: pdf, txt, md, json, xml, csv, doc, docx, xls, xlsx, ppt, pptx", 
                    "压缩包: zip, rar, 7z, tar, gz, bz2, xz",
                    "音频: mp3, wav, flac, aac, ogg, wma",
                    "视频: mp4, avi, mov, wmv, flv, mkv, webm",
                    "其他: html, css, js, sql, log"
                },
                "uploadDirectories", new String[]{
                    "covers", "images", "documents", 
                    "videos", "audios", "uploads"
                },
                "tips", "兼容接口：文件将与用户端文件存储在同一目录下。建议使用新版 /admin/oss/* 接口获得更完整的功能。"
            );
            
            return Result.success(config, "获取上传配置成功");
        } catch (Exception e) {
            log.error("获取上传配置失败: {}", e.getMessage(), e);
            return Result.error(500, "获取上传配置失败");
        }
    }
}
