// Package web is the HTTP admin panel: login (JWT), dashboard, user/key/proxy
// management, settings and a live log view. Templates are embedded so the
// shipped binary is fully self-contained.
package web

import (
	"database/sql"
	"errors"
	"html/template"
	"net/http"
	"strings"
	"time"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"

	"github.com/z/tg-apicreator-bot/internal/config"
	"github.com/z/tg-apicreator-bot/internal/logging"
	"github.com/z/tg-apicreator-bot/internal/proxy"
	"github.com/z/tg-apicreator-bot/internal/ratelimit"
	"github.com/z/tg-apicreator-bot/internal/repository"
)

// Server holds all the collaborators the handlers need.
type Server struct {
	cfg     *config.Config
	repo    *repository.Repository
	proxies *proxy.Manager
	limiter *ratelimit.Limiter
	logger  *logging.Logger
	botName string

	templates map[string]*template.Template
}

// New returns a configured gin engine. botName is the @username of the bot,
// shown in the dashboard as a deep-link target.
func New(cfg *config.Config, repo *repository.Repository, pm *proxy.Manager, lim *ratelimit.Limiter, lg *logging.Logger, botName string) *gin.Engine {
	gin.SetMode(gin.ReleaseMode)
	r := gin.New()
	r.Use(gin.Recovery())
	r.Use(cors.Default())

	srv := &Server{cfg: cfg, repo: repo, proxies: pm, limiter: lim, logger: lg, botName: botName}

	// Make sure the admin password is bootstrapped as a bcrypt hash on first run.
	if err := srv.bootstrapPassword(); err != nil {
		lg.Warnf("web", "bootstrap password: %v", err)
	}

	// Templates are parsed per-page (layout + page) so each page owns its own
	// "content" block without conflicts. The map is consulted by render().
	tmpls, err := loadTemplates()
	if err != nil {
		panic("load templates: " + err.Error())
	}
	srv.templates = tmpls

	// Public routes.
	r.GET("/healthz", srv.healthz)
	r.GET("/login", srv.showLogin)
	r.POST("/login", srv.doLogin)
	r.GET("/logout", srv.doLogout)

	// Everything below requires a valid JWT.
	authed := r.Group("/", srv.requireAuth)
	authed.GET("/", srv.dashboard)
	authed.GET("/users", srv.usersPage)
	authed.GET("/apikeys", srv.apikeysPage)
	authed.GET("/proxies", srv.proxiesPage)
	authed.GET("/settings", srv.settingsPage)
	authed.GET("/logs", srv.logsPage)

	// JSON API used by the page JS.
	api := authed.Group("/api")
	api.GET("/stats", srv.apiStats)
	api.GET("/logs", srv.apiLogs)
	api.POST("/users/:tg/ban", srv.apiBanUser)
	api.POST("/users/:tg/unban", srv.apiUnbanUser)
	api.POST("/apikeys/:id/revoke", srv.apiRevokeKey)
	api.POST("/apikeys/:id/delete", srv.apiDeleteKey)
	api.POST("/proxies", srv.apiAddProxy)
	api.POST("/proxies/:id/toggle", srv.apiToggleProxy)
	api.POST("/proxies/:id/delete", srv.apiDeleteProxy)
	api.POST("/settings", srv.apiSaveSettings)
	api.POST("/password", srv.apiChangePassword)

	return r
}

// ---- auth middleware ----

const (
	jwtCookie = "tg_admin_session"
	jwtTTL    = 12 * time.Hour
)

type claims struct {
	Username string `json:"username"`
	jwt.RegisteredClaims
}

// requireAuth rejects any request without a valid session cookie. On success
// the username is stored in the gin context for templates.
func (s *Server) requireAuth(c *gin.Context) {
	cookie, err := c.Cookie(jwtCookie)
	if err != nil || cookie == "" {
		c.Redirect(http.StatusFound, "/login")
		c.Abort()
		return
	}
	tok, err := jwt.ParseWithClaims(cookie, &claims{}, func(t *jwt.Token) (any, error) {
		if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, errors.New("unexpected signing method")
		}
		return []byte(s.cfg.Web.JWTSecret), nil
	})
	if err != nil || !tok.Valid {
		c.Redirect(http.StatusFound, "/login")
		c.Abort()
		return
	}
	if cl, ok := tok.Claims.(*claims); ok {
		c.Set("username", cl.Username)
	}
	c.Next()
}

// issueToken creates a signed JWT and tells the caller to set it as a cookie.
func (s *Server) issueToken(username string) (string, error) {
	now := time.Now()
	cl := claims{
		Username: username,
		RegisteredClaims: jwt.RegisteredClaims{
			IssuedAt:  jwt.NewNumericDate(now),
			ExpiresAt: jwt.NewNumericDate(now.Add(jwtTTL)),
			Issuer:    s.cfg.Web.BaseURL,
		},
	}
	tok := jwt.NewWithClaims(jwt.SigningMethodHS256, cl)
	return tok.SignedString([]byte(s.cfg.Web.JWTSecret))
}

// realIP extracts the client IP, honoring the configured reverse-proxy header.
func (s *Server) realIP(c *gin.Context) string {
	if h := strings.TrimSpace(s.cfg.Web.RealIPHeader); h != "" {
		if v := c.GetHeader(h); v != "" {
			return strings.TrimSpace(strings.Split(v, ",")[0])
		}
	}
	return c.ClientIP()
}

// healthz is a trivial liveness probe used by the Docker healthcheck.
func (s *Server) healthz(c *gin.Context) {
	c.String(http.StatusOK, "ok")
}

// Used by handler helpers.
var _ = sql.ErrNoRows
