package web

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
)

// setting keys stored in the `settings` table.
const (
	settingAdminPass = "web_admin_password"
)

// bootstrapPassword hashes the plaintext admin password from the config and
// persists it the first time the panel boots. After that the stored hash is
// the source of truth, so the config value is only used for initial setup.
func (s *Server) bootstrapPassword() error {
	stored, err := s.repo.GetSetting(settingAdminPass)
	if err != nil {
		return err
	}
	if stored != "" {
		return nil
	}
	pw := s.cfg.Web.AdminPassword
	if pw == "" {
		return nil
	}
	hash, err := bcrypt.GenerateFromPassword([]byte(pw), bcrypt.DefaultCost)
	if err != nil {
		return err
	}
	return s.repo.SetSetting(settingAdminPass, string(hash))
}

// verifyPassword checks the submitted password against the stored bcrypt hash
// (falling back to the plaintext config value if the hash is missing).
func (s *Server) verifyPassword(submitted string) bool {
	stored, _ := s.repo.GetSetting(settingAdminPass)
	if stored != "" {
		return bcrypt.CompareHashAndPassword([]byte(stored), []byte(submitted)) == nil
	}
	// No stored hash yet: compare against the config plaintext as a fallback.
	return submitted != "" && submitted == s.cfg.Web.AdminPassword
}

// showLogin renders the login page.
func (s *Server) showLogin(c *gin.Context) {
	s.render(c, "login.html", http.StatusOK, pageData{
		Title: "Login",
	})
}

// doLogin validates credentials and issues a JWT cookie.
func (s *Server) doLogin(c *gin.Context) {
	user := c.PostForm("username")
	pass := c.PostForm("password")

	if user != s.cfg.Web.AdminUser || !s.verifyPassword(pass) {
		s.logger.Warnf("web", "failed login attempt from %s (user=%q)", s.realIP(c), user)
		s.render(c, "login.html", http.StatusUnauthorized, pageData{
			Title: "Login",
			Error: "Invalid credentials",
		})
		return
	}

	tok, err := s.issueToken(user)
	if err != nil {
		s.logger.Errorf("web", "issue token: %v", err)
		s.render(c, "login.html", http.StatusInternalServerError, pageData{
			Title: "Login",
			Error: "Internal error",
		})
		return
	}

	c.SetCookie(jwtCookie, tok, int(jwtTTL.Seconds()), "/", "", false, true)
	s.logger.Infof("web", "admin %q logged in from %s", user, s.realIP(c))
	c.Redirect(http.StatusFound, "/")
}

// doLogout clears the session cookie.
func (s *Server) doLogout(c *gin.Context) {
	c.SetCookie(jwtCookie, "", -1, "/", "", false, true)
	c.Redirect(http.StatusFound, "/login")
}

// apiChangePassword lets the admin set a new web password.
func (s *Server) apiChangePassword(c *gin.Context) {
	pw := c.PostForm("password")
	if len(pw) < 6 {
		c.JSON(http.StatusBadRequest, gin.H{"ok": false, "error": "password must be at least 6 chars"})
		return
	}
	hash, err := bcrypt.GenerateFromPassword([]byte(pw), bcrypt.DefaultCost)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"ok": false, "error": err.Error()})
		return
	}
	if err := s.repo.SetSetting(settingAdminPass, string(hash)); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"ok": false, "error": err.Error()})
		return
	}
	s.logger.Infof("web", "admin password changed from %s", s.realIP(c))
	c.JSON(http.StatusOK, gin.H{"ok": true})
}
