package biz

import (
	"context"
	"fmt"
	"github.guxuan/haibei/internal/config"
	"github.guxuan/haibei/pkg/cachex"
	"github.guxuan/haibei/pkg/util"
	"io"
	"mime/multipart"
	"os"
	"path/filepath"
	"strings"
)

// Role management for RBAC
type Upload struct {
	Cache cachex.Cacher
	Trans *util.Trans
}

func (a *Upload) SaveFile(ctx context.Context, file *multipart.FileHeader) (string, error) {
	ext := strings.ToLower(filepath.Ext(file.Filename))
	// 简单过滤危险扩展名
	blacklist := []string{".exe", ".bat", ".sh", ".php", ".js"}
	for _, b := range blacklist {
		if ext == b {
			return "", fmt.Errorf("不支持的文件类型: %s", ext)
		}
	}
	// 确保上传目录存在
	if err := os.MkdirAll(config.C.FileConfig.UploadDir, os.ModePerm); err != nil {
		return "", err
	}
	// 构造保存路径
	dstPath := filepath.Join(config.C.FileConfig.UploadDir, file.Filename)
	// 打开源文件
	srcFile, err := file.Open()
	if err != nil {
		return "", err
	}
	defer srcFile.Close()
	// 在目标位置创建文件
	outFile, err := os.Create(dstPath)
	if err != nil {
		return "", err
	}
	defer outFile.Close()
	// 复制内容
	if _, err := io.Copy(outFile, srcFile); err != nil {
		return "", err
	}
	return file.Filename, nil
}
