package com.jeesharp.business.modules.tool.controller;

import com.jeesharp.business.modules.tool.application.ImageToolApplicationService;
import com.jeesharp.business.modules.tool.dto.ImageProcessDTO;
import com.jeesharp.business.modules.tool.vo.ImageAnalysisVO;
import com.jeesharp.business.modules.tool.vo.ImageProcessResultVO;
import com.jeesharp.framework.pojo.AjaxResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 图片工具控制器
 */
@Tag(name = "图片工具", description = "图片处理工具接口")
@RestController
@RequestMapping("${jeesharp.web.adminPath}/manager/business/tool/image/v1")
@RequiredArgsConstructor
public class ImageToolController {

    private final ImageToolApplicationService imageToolApplicationService;

    @Operation(summary = "分析图片", description = "分析图片并返回智能推荐参数")
    @PostMapping("/analyze")
    public AjaxResult<ImageAnalysisVO> analyzeImage(
            @Parameter(description = "图片文件", required = true)
            @RequestParam("file") MultipartFile file) {
        ImageAnalysisVO result = imageToolApplicationService.analyzeImage(file);
        return AjaxResult.okData(result);
    }

    @Operation(summary = "处理图片并上传", description = "处理图片（缩放、格式转换、质量压缩）并上传到文件存储")
    @PostMapping("/process")
    public AjaxResult<ImageProcessResultVO> processImage(
            @Parameter(description = "图片文件", required = true)
            @RequestParam("file") MultipartFile file,
            @Valid ImageProcessDTO dto) {
        ImageProcessResultVO result = imageToolApplicationService.processAndUpload(file, dto);
        return AjaxResult.okData(result);
    }

    @Operation(summary = "处理图片并下载", description = "处理图片（缩放、格式转换、质量压缩）并返回文件流")
    @PostMapping("/download")
    public ResponseEntity<byte[]> downloadImage(
            @Parameter(description = "图片文件", required = true)
            @RequestParam("file") MultipartFile file,
            @Valid ImageProcessDTO dto) {
        byte[] imageBytes = imageToolApplicationService.processForDownload(file, dto);

        // 确定文件名
        String format = dto.getFormat();
        String extension = "jpeg".equals(format) ? "jpg" : format;
        String originalName = file.getOriginalFilename();
        String baseName = originalName != null ? originalName.substring(0, originalName.lastIndexOf('.')) : "processed-image";
        String fileName = baseName + "_processed." + extension;

        // 确定 Content-Type
        String contentType;
        switch (format) {
            case "png":
                contentType = MediaType.IMAGE_PNG_VALUE;
                break;
            case "gif":
                contentType = MediaType.IMAGE_GIF_VALUE;
                break;
            case "webp":
                contentType = "image/webp";
                break;
            default:
                contentType = MediaType.IMAGE_JPEG_VALUE;
                break;
        }

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                .body(imageBytes);
    }
}
