package com.toyshop.controller.admin;

import com.toyshop.dto.ApiResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@RequestMapping("/api/admin")
@PreAuthorize("hasRole('ADMIN')")
public class UploadController {
  @Value("${app.upload.dir}")
  private String uploadDir;

  @PostMapping("/upload")
  public ApiResponse<?> upload(@RequestParam("file") MultipartFile file) throws IOException {
    if (file.isEmpty()) {
      return ApiResponse.fail("文件为空");
    }
    String original = file.getOriginalFilename();
    String ext = StringUtils.getFilenameExtension(original);
    String filename = UUID.randomUUID().toString().replace("-", "");
    if (ext != null && !ext.isBlank()) {
      filename = filename + "." + ext;
    }
    Path target = Paths.get(uploadDir, filename);
    Files.createDirectories(target.getParent());
    file.transferTo(target);
    String url = "/files/" + filename;
    return ApiResponse.ok(url);
  }
}
