package main

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

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

func dataBasePath() string { return getEnv("DATA_DIR", "data") }
func dbPath() string       { return filepath.Join(dataBasePath(), "mengyaconnect.db") }

// accessPassword 返回 Web 访问密码，可通过 ACCESS_PASSWORD 环境变量覆盖
func accessPassword() string { return getEnv("ACCESS_PASSWORD", "shumengya520") }

// apiVersion 根路径 JSON 中的版本号，可由 API_VERSION 覆盖
func apiVersion() string { return getEnv("API_VERSION", "1.0.0-go") }

// validateName 检查名称合法性（防止空/路径穿越等），不再依赖 filepath.Base
func validateName(name string) error {
	name = strings.TrimSpace(name)
	if name == "" || name == "." || name == ".." || strings.ContainsAny(name, "/\\") {
		return errors.New("invalid name")
	}
	return 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
}
