package admin

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

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

//go:embed web/*
var adminWeb embed.FS

func adminIndex(adminDir string) ([]byte, error) {
	if strings.TrimSpace(adminDir) != "" {
		path := filepath.Join(adminDir, "index.html")
		if page, err := os.ReadFile(path); err == nil {
			return rewriteAdminBase(page), nil
		}
	}
	return adminWeb.ReadFile("web/index.html")
}

func serveAdminFile(c *gin.Context, adminDir string) bool {
	if strings.TrimSpace(adminDir) == "" {
		return false
	}

	requested := strings.TrimPrefix(c.Param("filepath"), "/")
	if requested == "" {
		return false
	}
	cleaned := filepath.Clean(requested)
	if cleaned == "." || strings.HasPrefix(cleaned, "..") {
		return false
	}

	path := filepath.Join(adminDir, cleaned)
	info, err := os.Stat(path)
	if err != nil || info.IsDir() {
		return false
	}
	http.ServeFile(c.Writer, c.Request, path)
	return true
}

func serveSiteFile(c *gin.Context, staticDir string) bool {
	if strings.TrimSpace(staticDir) == "" {
		return false
	}

	requested := strings.TrimPrefix(c.Request.URL.Path, "/")
	if requested == "" {
		requested = "index.html"
	}
	cleaned := filepath.Clean(requested)
	if cleaned == "." || strings.HasPrefix(cleaned, "..") || filepath.IsAbs(cleaned) {
		return false
	}

	path := filepath.Join(staticDir, cleaned)
	info, err := os.Stat(path)
	if err == nil && info.IsDir() {
		path = filepath.Join(path, "index.html")
		info, err = os.Stat(path)
	}
	if err != nil || info.IsDir() {
		return false
	}
	http.ServeFile(c.Writer, c.Request, path)
	return true
}

func rewriteAdminBase(page []byte) []byte {
	return []byte(strings.Replace(string(page), `<base href="/">`, `<base href="/admin/">`, 1))
}
