package com.yaoai.api.controller;

import com.yaoai.common.exception.BizException;
import com.yaoai.common.exception.ErrorCode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.CacheControl;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@Profile("dev-h2")
public class LocalFilesController {

    private final Path rootDir;

    public LocalFilesController(@Value("${local-storage.base-dir:./.local-data/storage}") String baseDir) {
        this.rootDir = Paths.get(baseDir).toAbsolutePath().normalize();
    }

    @GetMapping("/local-files")
    public ResponseEntity<Resource> get(@RequestParam String key) {
        Path file = resolveKey(key);
        if (!Files.isRegularFile(file)) {
            throw new BizException(ErrorCode.NOT_FOUND, "本地文件不存在");
        }

        return ResponseEntity.ok()
                .cacheControl(CacheControl.noStore())
                .contentType(MediaType.parseMediaType(probeContentType(file)))
                .body(new FileSystemResource(file));
    }

    private Path resolveKey(String key) {
        Path path = rootDir.resolve(key).normalize();
        if (!path.startsWith(rootDir)) {
            throw new BizException(ErrorCode.INVALID_PARAM, "非法文件路径");
        }
        return path;
    }

    private String probeContentType(Path file) {
        try {
            String detected = Files.probeContentType(file);
            return detected == null || detected.isBlank() ? MediaType.APPLICATION_OCTET_STREAM_VALUE : detected;
        } catch (IOException e) {
            return MediaType.APPLICATION_OCTET_STREAM_VALUE;
        }
    }
}
