package com.ruoyi.cc.controller;

import com.ruoyi.aicall.utils.ClientIpCheck;
import com.ruoyi.cc.service.ICcParamsService;
import com.ruoyi.cc.utils.RecordingPathUtils;
import com.ruoyi.cc.utils.RecordingPathUtils.FileResolveResult;
import com.ruoyi.cc.utils.RecordingPathUtils.ResolveStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

/**
 * 录音文件访问
 */
@Controller
@RequestMapping("/recordings")
public class RecordingFileController extends BaseController {
    @Autowired
    private ICcParamsService ccParamsService;

    @GetMapping("/files")
    public ResponseEntity<Resource> downloadFile(@RequestParam String filename, HttpServletRequest request) {
        if (!ClientIpCheck.checkIp(request)) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
        if (StringUtils.isEmpty(filename)) {
            return ResponseEntity.badRequest().build();
        }
        try {
            String wavBasePath = ccParamsService.getParamValueByCode(
                    "recording_path", "/home/Records/");
            FileResolveResult resolved = RecordingPathUtils.resolveReadableRecordingFile(wavBasePath, filename);
            if (resolved.getStatus() == ResolveStatus.FORBIDDEN) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
            }
            if (resolved.getStatus() == ResolveStatus.NOT_FOUND) {
                return ResponseEntity.notFound().build();
            }
            if (resolved.getStatus() != ResolveStatus.OK || resolved.getPath() == null) {
                return ResponseEntity.badRequest().build();
            }
            Resource resource = new UrlResource(resolved.getPath().toUri());
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION,
                            "attachment; filename=\"" + resource.getFilename() + "\"")
                    .body(resource);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
}
