package main

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

	"github.com/gin-gonic/gin"
)

// 数据目录辅助
func dataBasePath() string { return getEnv("DATA_DIR", "data") }
func sshDir() string       { return filepath.Join(dataBasePath(), "ssh") }
func cmdFilePath() string  { return filepath.Join(dataBasePath(), "command", "command.json") }
func scriptDir() string    { return filepath.Join(dataBasePath(), "script") }

// sanitizeName 防止路径穿越攻击
func sanitizeName(name string) (string, error) {
	base := filepath.Base(name)
	if base == "" || base == "." || base == ".." {
		return "", errors.New("invalid name")
	}
	return base, nil
}

func corsMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
		if c.Request.Method == http.MethodOptions {
			c.AbortWithStatus(http.StatusNoContent)
			return
		}
		c.Next()
	}
}

func isOriginAllowed(origin string, allowed []string) bool {
	if origin == "" {
		return true
	}
	if len(allowed) == 0 {
		return true
	}
	for _, item := range allowed {
		if item == "*" || strings.EqualFold(strings.TrimSpace(item), origin) {
			return true
		}
	}
	return false
}

func parseListEnv(name string) []string {
	raw := strings.TrimSpace(os.Getenv(name))
	if raw == "" {
		return nil
	}
	parts := strings.Split(raw, ",")
	out := make([]string, 0, len(parts))
	for _, part := range parts {
		part = strings.TrimSpace(part)
		if part != "" {
			out = append(out, part)
		}
	}
	return out
}

func getEnv(key, fallback string) string {
	if val := strings.TrimSpace(os.Getenv(key)); val != "" {
		return val
	}
	return fallback
}

