package com.artfess.rescue.open.controller;

import com.aliyun.oss.common.utils.HttpHeaders;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/voices")
public class VoiceController {

    @GetMapping("/{filename}")
    public ResponseEntity<Resource> serveVoiceFile(@PathVariable String filename) {
        try {
            // 1. 从临时目录加载文件
            Path filePath = Paths.get(System.getProperty("java.io.tmpdir"), "voice_files", filename);
            Resource resource = new FileSystemResource(filePath);
            // 2. 设置正确的Content-Type
            String contentType = filename.endsWith(".mp3") ? "audio/mpeg" : "audio/wav";
            return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType)).header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\"").body(resource);
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }
}
