package com.example.demo.attachment;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
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 java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/attachments")
public class AttachmentController {

	private final AttachmentPlaceholderProperties placeholderProperties;

	public AttachmentController(AttachmentPlaceholderProperties placeholderProperties) {
		this.placeholderProperties = placeholderProperties;
	}

	@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
	public ResponseEntity<Map<String, Object>> upload(@RequestParam("file") MultipartFile file,
													 @RequestParam(value = "ownerType", required = false) String ownerType,
													 @RequestParam(value = "ownerId", required = false) String ownerId) {
		// 占位实现：忽略文件内容，始终返回占位图 URL
		String url = StringUtils.hasText(placeholderProperties.getUrlPath()) ? placeholderProperties.getUrlPath() : "/api/attachments/placeholder";
		Map<String, Object> body = new HashMap<>();
		body.put("url", url);
		return ResponseEntity.ok(body);
	}

	@GetMapping("/placeholder")
	public ResponseEntity<Resource> placeholder() throws IOException {
		String imagePath = placeholderProperties.getImagePath();
		if (!StringUtils.hasText(imagePath)) {
			return ResponseEntity.status(404).build();
		}
		Path path = Path.of(imagePath);
		if (!Files.exists(path)) {
			return ResponseEntity.status(404).build();
		}
		Resource resource = new FileSystemResource(path);
		String contentType = Files.probeContentType(path);
		MediaType mediaType;
		try {
			mediaType = StringUtils.hasText(contentType) ? MediaType.parseMediaType(contentType) : MediaType.IMAGE_PNG;
		} catch (Exception e) {
			mediaType = MediaType.APPLICATION_OCTET_STREAM;
		}
		return ResponseEntity.ok()
				.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=placeholder")
				.cacheControl(CacheControl.maxAge(30, TimeUnit.DAYS).cachePublic())
				.contentType(mediaType)
				.body(resource);
	}
}







