package com.nailart.controller;


import com.nailart.service.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Description 文件服务控制类
 * @Classname FileStorageController
 * @Date 2025/7/19 15:47
 * @Created by 21616
 */
@RestController
@RequestMapping("/file")
public class FileStorageController {

    private final FileStorageService fileStorageService;

    @Autowired
    public FileStorageController(FileStorageService fileStorageService) {
        this.fileStorageService = fileStorageService;
    }

    /**
     * 上传文件
     * @param bucketName 存储桶名称
     * @param filePath 文件路径
     * @param file 文件内容
     * @return 上传成功的文件路径
     */
    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(
            @RequestParam("bucketName") String bucketName,
            @RequestParam("filePath") String filePath,
            @RequestParam("file") MultipartFile file) {

        String uploadedFilePath = fileStorageService.uploadFile(bucketName, filePath, file);
        return ResponseEntity.ok(uploadedFilePath);
    }

    /**
     * 下载文件
     * @param bucketName 存储桶名称
     * @param filePath 文件路径
     * @return 文件内容流
     */
    @GetMapping("/download")
    public ResponseEntity<InputStream> downloadFile(
            @RequestParam("bucketName") String bucketName,
            @RequestParam("filePath") String filePath) {

        try {
            InputStream fileStream = fileStorageService.downloadFile(bucketName, filePath);

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

            // 处理中文文件名编码
            String encodedFileName = URLEncoder.encode(filePath.substring(filePath.lastIndexOf("/") + 1),
                    StandardCharsets.UTF_8).replaceAll("\\+", "%20");
            headers.setContentDispositionFormData("attachment", encodedFileName);

            return new ResponseEntity<>(fileStream, headers, HttpStatus.OK);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }

    /**
     * 删除文件
     * @param bucketName 存储桶名称
     * @param filePath 文件路径
     * @return 操作结果
     */
    @DeleteMapping("/delete")
    public ResponseEntity<Void> deleteFile(
            @RequestParam("bucketName") String bucketName,
            @RequestParam("filePath") String filePath) {

        fileStorageService.deleteFile(bucketName, filePath);
        return ResponseEntity.noContent().build();
    }

    /**
     * 检查文件是否存在
     * @param bucketName 存储桶名称
     * @param filePath 文件路径
     * @return 文件是否存在
     */
    @GetMapping("/exists")
    public ResponseEntity<Boolean> fileExists(
            @RequestParam("bucketName") String bucketName,
            @RequestParam("filePath") String filePath) {

        boolean exists = fileStorageService.fileExists(bucketName, filePath);
        return ResponseEntity.ok(exists);
    }

    /**
     * 获取文件的预签名URL
     * @param bucketName 存储桶名称
     * @param filePath 文件路径
     * @param expirySeconds 过期时间（秒）
     * @return 预签名URL
     */
    @GetMapping("/url")
    public ResponseEntity<String> getFileUrl(
            @RequestParam("bucketName") String bucketName,
            @RequestParam("filePath") String filePath,
            @RequestParam(value = "expirySeconds", defaultValue = "3600") int expirySeconds) {

        String url = fileStorageService.getFileUrl(bucketName, filePath, expirySeconds);
        return ResponseEntity.ok(url);
    }

    /**
     * 获取所有存储桶列表
     * @return 存储桶名称列表
     */
    @GetMapping("/buckets")
    public ResponseEntity<List<String>> listBuckets() {
        List<String> buckets = fileStorageService.listBuckets();
        return ResponseEntity.ok(buckets);
    }

    /**
     * 创建存储桶
     * @param bucketName 存储桶名称
     * @return 操作结果
     */
    @PostMapping("/buckets")
    public ResponseEntity<Void> createBucket(@RequestParam("bucketName") String bucketName) {
        fileStorageService.createBucket(bucketName);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 删除存储桶
     * @param bucketName 存储桶名称
     * @return 操作结果
     */
    @DeleteMapping("/buckets")
    public ResponseEntity<Void> deleteBucket(@RequestParam("bucketName") String bucketName) {
        fileStorageService.deleteBucket(bucketName);
        return ResponseEntity.noContent().build();
    }

    /**
     * 检查存储桶是否存在
     * @param bucketName 存储桶名称
     * @return 存储桶是否存在
     */
    @GetMapping("/buckets/exists")
    public ResponseEntity<Boolean> bucketExists(@RequestParam("bucketName") String bucketName) {
        boolean exists = fileStorageService.bucketExists(bucketName);
        return ResponseEntity.ok(exists);
    }
}
