package initialize

import (
	"net/http"
	"os"

	"kra/internal/conf"

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

// justFilesFilesystem 只允许访问文件的文件系统
type justFilesFilesystem struct {
	fs http.FileSystem
}

func (fs justFilesFilesystem) Open(name string) (http.File, error) {
	f, err := fs.fs.Open(name)
	if err != nil {
		return nil, err
	}

	stat, err := f.Stat()
	if err != nil {
		f.Close()
		return nil, err
	}

	if stat.IsDir() {
		f.Close()
		return nil, os.ErrPermission
	}

	return f, nil
}

// RouterConfig 路由配置
type RouterConfig struct {
	RouterPrefix string
	StorePath    string
	SwaggerPath  string
}

// NewRouterConfig 创建路由配置
func NewRouterConfig(system *conf.System, local *conf.Local) *RouterConfig {
	cfg := &RouterConfig{
		RouterPrefix: "",
		StorePath:    "uploads/file",
		SwaggerPath:  "/swagger/*any",
	}

	if system != nil {
		cfg.RouterPrefix = system.RouterPrefix
	}

	if local != nil && local.StorePath != "" {
		cfg.StorePath = local.StorePath
	}

	return cfg
}

// SetupStaticFiles 设置静态文件服务
func SetupStaticFiles(engine *gin.Engine, storePath string) {
	if storePath != "" {
		engine.StaticFS(storePath, justFilesFilesystem{http.Dir(storePath)})
	}
}

// SetupHealthCheck 设置健康检查端点
func SetupHealthCheck(group *gin.RouterGroup) {
	group.GET("/health", func(c *gin.Context) {
		c.JSON(http.StatusOK, "ok")
	})
}

// RouterGroups 路由组集合
type RouterGroups struct {
	Public  *gin.RouterGroup
	Private *gin.RouterGroup
}

// NewRouterGroups 创建路由组
func NewRouterGroups(engine *gin.Engine, prefix string) *RouterGroups {
	return &RouterGroups{
		Public:  engine.Group(prefix),
		Private: engine.Group(prefix),
	}
}

// RouteInfo 路由信息
type RouteInfo struct {
	Method      string
	Path        string
	Handler     string
	HandlerFunc gin.HandlerFunc
}

// Routes 路由列表
type Routes []RouteInfo

// GetRoutes 获取所有路由信息
func GetRoutes(engine *gin.Engine) gin.RoutesInfo {
	return engine.Routes()
}
