package com.moka.gdtauto.controller;

import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.moka.gdtauto.annotation.AuthUser;
import com.moka.gdtauto.common.Result;
import com.moka.gdtauto.entity.OssFile;
import com.moka.gdtauto.entity.SysUser;
import com.moka.gdtauto.service.OssFileService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * OSS文件管理Controller
 *
 * @author moka
 * @since 2026-02-26
 */
@Tag(name = "OSS文件管理", description = "OSS文件的上传、删除及查询")
@Slf4j
@RestController
@RequestMapping("/api/oss-file")
@RequiredArgsConstructor
public class OssFileController {

    private final OssFileService ossFileService;

    /**
     * 上传文件
     */
    @Operation(summary = "上传文件", description = "上传文件到OSS并记录")
    @PostMapping("/upload")
    public Result<OssFile> uploadFile(
            @Parameter(description = "文件", required = true)
            @RequestParam("file") MultipartFile file,
            @Parameter(description = "存储文件夹路径，如：images/、videos/")
            @RequestParam(value = "folder", required = false, defaultValue = "") String folder,
            @Parameter(description = "文件类型，如：image、video、document")
            @RequestParam(value = "fileType", required = false, defaultValue = "document") String fileType,
            @ToolParam(description = "业务分类(1:创意 2:品牌形象)")
            @Parameter(description = "业务分类(1:创意 2:品牌形象)")
            @RequestParam(value = "businessType", required = false) Integer businessType,
            @AuthUser SysUser sysUser) {
        try {
            if (file.isEmpty()) {
                return Result.fail("文件不能为空");
            }
            
            OssFile ossFile = ossFileService.uploadFile(
                    file, 
                    folder, 
                    fileType,
                    businessType,
                    sysUser.getId(), 
                    sysUser.getName()
            );
            
            return Result.success(ossFile, "文件上传成功");
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return Result.fail("文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 分页查询文件列表
     */
    @Operation(summary = "分页查询文件列表", description = "根据条件分页查询文件列表")
    @GetMapping("/list")
    public Result<Page<OssFile>> listFiles(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Long page,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Long size,
            @Parameter(description = "文件类型") @RequestParam(required = false) String fileType,
            @Parameter(description = "业务分类(1:创意 2:品牌形象)") @RequestParam(required = false) Integer businessType,
            @Parameter(description = "文件名（模糊查询）") @RequestParam(required = false) String fileName,
            @Parameter(description = "创建人id") @RequestParam(required = false) Long userId,
            @Parameter(description = "排序字段(如: normalCnt, deniedCnt)") @RequestParam(required = false) String sortField,
            @Parameter(description = "排序方式(ascending/descending)") @RequestParam(required = false) String sortOrder) {
        try {
            Page<OssFile> result = ossFileService.listFiles(page, size, fileType, businessType, fileName, userId, sortField, sortOrder);
            return Result.success(result);
        } catch (Exception e) {
            log.error("查询文件列表失败", e);
            return Result.fail("查询文件列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID查询文件详情
     */
    @Operation(summary = "查询文件详情", description = "根据ID查询文件详情")
    @GetMapping("/{id}")
    public Result<OssFile> getById(
            @Parameter(description = "文件ID", required = true)
            @PathVariable Long id) {
        try {
            OssFile ossFile = ossFileService.getById(id);
            if (ossFile == null) {
                return Result.fail("文件不存在");
            }
            return Result.success(ossFile);
        } catch (Exception e) {
            log.error("查询文件详情失败，ID: {}", id, e);
            return Result.fail("查询文件详情失败: " + e.getMessage());
        }
    }

    /**
     * 删除文件
     */
    @Operation(summary = "删除文件", description = "删除OSS文件及数据库记录")
    @DeleteMapping("/{id}")
    public Result<Void> deleteFile(
            @Parameter(description = "文件ID", required = true)
            @PathVariable Long id) {
        try {
            boolean success = ossFileService.deleteFile(id);
            if (success) {
                return Result.success("文件删除成功");
            } else {
                return Result.fail("文件不存在或删除失败");
            }
        } catch (Exception e) {
            log.error("文件删除失败，ID: {}", id, e);
            return Result.fail("文件删除失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除文件
     */
    @Operation(summary = "批量删除文件", description = "批量删除多个文件")
    @DeleteMapping("/batch")
    public Result<Void> batchDeleteFiles(
            @Parameter(description = "文件ID数组", required = true)
            @RequestParam Long[] fileIds) {
        try {
            boolean success = ossFileService.batchDeleteFiles(fileIds);
            if (success) {
                return Result.success("批量删除成功");
            } else {
                return Result.fail("批量删除失败，部分文件可能删除失败");
            }
        } catch (Exception e) {
            log.error("批量删除文件失败", e);
            return Result.fail("批量删除文件失败: " + e.getMessage());
        }
    }
}
