package web

import (
	"embed"
	"html/template"
	"net/http"
	"path"
	"strings"

	"github.com/gin-gonic/gin"

	"github.com/z/tg-apicreator-bot/internal/database"
	"github.com/z/tg-apicreator-bot/internal/repository"
)

//go:embed templates/*.html
var templateFS embed.FS

// pageData is the common payload every template receives.
type pageData struct {
	Title      string
	Base       string
	User       string
	Active     string
	BotName    string
	Stats      repository.Stats
	Users      []database.User
	UsersTotal int
	Keys       []database.APIKey
	KeysTotal  int
	Proxies    []database.Proxy
	Logs       []database.LogEntry
	LogsTotal  int
	Settings   settingsView
	Error      string
	Flash      string
}

// settingsView is the runtime-overridable part of the config shown on the
// settings page. Values come from the live *config.Config (which the panel
// updates in place) so what the admin sees is what the bot uses.
type settingsView struct {
	Daily            int
	Cooldown         int
	WhitelistEnabled bool
	WhitelistCount   int
	ProxyMode        string
	ProxyTimeout     int
}

// loadTemplates parses layout.html together with each page so every page owns
// its "content" block. The returned map is keyed by page file base name.
func loadTemplates() (map[string]*template.Template, error) {
	entries, err := templateFS.ReadDir("templates")
	if err != nil {
		return nil, err
	}
	out := map[string]*template.Template{}
	for _, e := range entries {
		name := e.Name()
		if name == "layout.html" || !strings.HasSuffix(name, ".html") {
			continue
		}
		t, err := template.ParseFS(templateFS,
			path.Join("templates", "layout.html"),
			path.Join("templates", name))
		if err != nil {
			return nil, err
		}
		out[name] = t
	}
	return out, nil
}

// render executes the named page template with the given payload.
func (s *Server) render(c *gin.Context, name string, code int, data pageData) {
	data.Base = s.cfg.Web.BaseURL
	data.BotName = s.botName
	if u, ok := c.Get("username"); ok {
		if us, _ := u.(string); us != "" {
			data.User = us
		}
	}
	t, ok := s.templates[name]
	if !ok {
		c.String(http.StatusInternalServerError, "template not found: %s", name)
		return
	}
	c.Status(code)
	c.Header("Content-Type", "text/html; charset=utf-8")
	if err := t.ExecuteTemplate(c.Writer, "layout.html", data); err != nil {
		s.logger.Errorf("web", "render %s: %v", name, err)
	}
}
