package httpapi

import (
	"net/http"
	"os"
	"path/filepath"
	"strings"

	"github.com/easyai/easyai-ai-gateway/apps/api/internal/config"
)

// serveGeneratedStaticAsset godoc
// @Summary 获取本地生成资源
// @Description 从本地生成资源目录读取图片、视频等任务产物；不存在时返回 404。
// @Tags static
// @Produce octet-stream
// @Param asset path string true "资源文件名"
// @Success 200 {file} file
// @Failure 404 {string} string "Not Found"
// @Router /static/generated/{asset} [get]
func (s *Server) serveGeneratedStaticAsset(w http.ResponseWriter, r *http.Request) {
	s.serveLocalStaticAsset(w, r, s.cfg.LocalGeneratedStorageDir, config.DefaultLocalGeneratedStorageDir)
}

// serveUploadedStaticAsset godoc
// @Summary 获取本地上传资源
// @Description 从本地上传资源目录读取用户上传文件；不存在时返回 404。
// @Tags static
// @Produce octet-stream
// @Param asset path string true "资源文件名"
// @Success 200 {file} file
// @Failure 404 {string} string "Not Found"
// @Router /static/uploaded/{asset} [get]
func (s *Server) serveUploadedStaticAsset(w http.ResponseWriter, r *http.Request) {
	s.serveLocalStaticAsset(w, r, s.cfg.LocalUploadedStorageDir, config.DefaultLocalUploadedStorageDir)
}

func (s *Server) serveLocalStaticAsset(w http.ResponseWriter, r *http.Request, storageDir string, fallbackStorageDir string) {
	fileName := filepath.Base(strings.TrimSpace(r.PathValue("asset")))
	if fileName == "" || fileName == "." || fileName == ".." || fileName == string(filepath.Separator) {
		http.NotFound(w, r)
		return
	}
	storageDir = strings.TrimSpace(storageDir)
	if storageDir == "" {
		storageDir = fallbackStorageDir
	}
	filePath := filepath.Join(storageDir, fileName)
	info, err := os.Stat(filePath)
	if err != nil || info.IsDir() {
		http.NotFound(w, r)
		return
	}
	http.ServeFile(w, r, filePath)
}
