package httpx

import (
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"net/mail"
	"strings"
	"time"

	"bountyboard/internal/auth"
	"bountyboard/internal/domain"
	"bountyboard/internal/store"
	"bountyboard/internal/ulid"
)

func (s *Server) routesAuth(mux *http.ServeMux) {
	mux.HandleFunc("POST /api/v1/auth/register", s.handleRegister)
	mux.HandleFunc("POST /api/v1/auth/login", s.handleLogin)
	mux.Handle("POST /api/v1/auth/logout", s.authed(s.handleLogout))
	mux.Handle("POST /api/v1/auth/logout-all", s.authed(s.handleLogoutAll))
	mux.Handle("POST /api/v1/auth/change-password", s.authed(s.handleChangePassword))
	mux.Handle("GET /api/v1/auth/me", s.requireAuth(http.HandlerFunc(s.handleMe)))
	mux.HandleFunc("GET /api/v1/auth/oidc/login", s.handleOIDCLogin)
	mux.HandleFunc("GET /api/v1/auth/oidc/callback", s.handleOIDCCallback)
	mux.HandleFunc("POST /api/v1/auth/forgot", s.handleForgotPassword)
	mux.HandleFunc("POST /api/v1/auth/reset", s.handleResetPassword)
}

// handleForgotPassword issues a one-shot reset token by email (§11.22).
// Active only when SMTP is configured; never reveals account existence.
func (s *Server) handleForgotPassword(w http.ResponseWriter, r *http.Request) {
	var req struct {
		Email string `json:"email"`
	}
	if !decodeJSON(w, r, &req) {
		return
	}
	if s.mailer == nil || !s.mailer.Enabled() {
		writeError(w, http.StatusServiceUnavailable, "smtp_disabled",
			"password reset by email is not configured on this server")
		return
	}
	if !s.loginLimiter.Allow("forgot|" + ClientIP(r.Context()).String()) {
		writeError(w, http.StatusTooManyRequests, "rate_limited", "too many attempts")
		return
	}
	u, err := s.store.UserByEmail(r.Context(), req.Email)
	if err == nil && u.Auth.Local != nil && !u.Disabled {
		token := auth.NewToken()
		if err := s.store.CreatePasswordReset(r.Context(), token, u.ID, time.Hour); err != nil {
			s.internalError(w, r, "create reset", err)
			return
		}
		link := s.cfg.AppBaseURL + "/reset-password?token=" + token
		go func() {
			if err := s.mailer.Send(u.Email, "Reset your Bounty Board password",
				"Use this link within one hour to set a new password:\n\n"+link+
					"\n\nIf you did not request this, ignore this email."); err != nil {
				s.log.Error("send reset mail", "err", err)
			}
		}()
	}
	// uniform response regardless of account existence
	writeJSON(w, http.StatusOK, map[string]string{"status": "sent_if_account_exists"})
}

func (s *Server) handleResetPassword(w http.ResponseWriter, r *http.Request) {
	var req struct {
		Token       string `json:"token"`
		NewPassword string `json:"newPassword"`
	}
	if !decodeJSON(w, r, &req) {
		return
	}
	if len(req.NewPassword) < auth.MinPasswordLen {
		writeError(w, http.StatusBadRequest, "weak_password",
			fmt.Sprintf("password must be at least %d characters", auth.MinPasswordLen))
		return
	}
	userID, err := s.store.ConsumePasswordReset(r.Context(), req.Token)
	if err != nil {
		writeError(w, http.StatusBadRequest, "invalid_token", "this reset link is invalid or expired")
		return
	}
	hash, err := auth.HashPassword(req.NewPassword)
	if err != nil {
		s.internalError(w, r, "hash password", err)
		return
	}
	if err := s.store.SetPassword(r.Context(), userID, hash, false); err != nil {
		s.internalError(w, r, "set password", err)
		return
	}
	if _, err := s.store.DeleteUserSessions(r.Context(), userID); err != nil {
		s.log.Warn("revoke sessions after reset", "err", err)
	}
	w.WriteHeader(http.StatusNoContent)
}

// decodeJSON reads a bounded JSON body into dst, rejecting unknown fields.
func decodeJSON(w http.ResponseWriter, r *http.Request, dst any) bool {
	dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
	dec.DisallowUnknownFields()
	if err := dec.Decode(dst); err != nil {
		writeError(w, http.StatusBadRequest, "bad_request", "invalid JSON body: "+err.Error())
		return false
	}
	return true
}

func validEmail(email string) bool {
	a, err := mail.ParseAddress(email)
	return err == nil && a.Address == email
}

func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) {
	var req struct {
		Email    string `json:"email"`
		Name     string `json:"name"`
		Password string `json:"password"`
	}
	if !decodeJSON(w, r, &req) {
		return
	}
	req.Email = store.NormalizeEmail(req.Email)
	req.Name = strings.TrimSpace(req.Name)
	switch {
	case !validEmail(req.Email):
		writeError(w, http.StatusBadRequest, "invalid_email", "a valid email address is required")
		return
	case req.Name == "":
		writeError(w, http.StatusBadRequest, "invalid_name", "name is required")
		return
	case len(req.Password) < auth.MinPasswordLen:
		writeError(w, http.StatusBadRequest, "weak_password",
			fmt.Sprintf("password must be at least %d characters", auth.MinPasswordLen))
		return
	}
	if !s.loginLimiter.Allow("register|" + ClientIP(r.Context()).String()) {
		writeError(w, http.StatusTooManyRequests, "rate_limited", "too many attempts, try again later")
		return
	}

	hash, err := auth.HashPassword(req.Password)
	if err != nil {
		s.internalError(w, r, "hash password", err)
		return
	}
	u := &domain.User{
		ID:    ulid.New(),
		Email: req.Email,
		Name:  req.Name,
		// Open self-registration always creates a developer account (§3).
		Roles: domain.Roles{Developer: true},
		Auth:  domain.Auth{Local: &domain.LocalAuth{PasswordHash: hash}},
		Settings: domain.UserSettings{
			Theme:         "light",
			Notifications: domain.NotificationPrefs{Email: true, InApp: true},
		},
	}
	if err := s.store.CreateUser(r.Context(), u); err != nil {
		if errors.Is(err, store.ErrDuplicate) {
			writeError(w, http.StatusConflict, "email_taken", "an account with this email already exists")
			return
		}
		s.internalError(w, r, "create user", err)
		return
	}
	s.metrics.Inc("auth_registrations_total", 1)
	s.startSession(w, r, u, http.StatusCreated)
}

func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
	var req struct {
		Email    string `json:"email"`
		Password string `json:"password"`
	}
	if !decodeJSON(w, r, &req) {
		return
	}
	req.Email = store.NormalizeEmail(req.Email)
	if !s.loginLimiter.Allow(ClientIP(r.Context()).String() + "|" + req.Email) {
		s.metrics.Inc("auth_rate_limited_total", 1)
		writeError(w, http.StatusTooManyRequests, "rate_limited", "too many attempts, try again later")
		return
	}

	denyInvalid := func() {
		s.metrics.Inc("auth_login_failures_total", 1)
		writeError(w, http.StatusUnauthorized, "invalid_credentials", "invalid email or password")
	}
	u, err := s.store.UserByEmail(r.Context(), req.Email)
	if err != nil {
		if errors.Is(err, store.ErrNotFound) {
			denyInvalid()
			return
		}
		s.internalError(w, r, "find user", err)
		return
	}
	if u.Auth.Local == nil {
		denyInvalid()
		return
	}
	ok, err := auth.VerifyPassword(req.Password, u.Auth.Local.PasswordHash)
	if err != nil {
		s.internalError(w, r, "verify password", err)
		return
	}
	if !ok {
		denyInvalid()
		return
	}
	if u.Disabled {
		writeError(w, http.StatusForbidden, "account_disabled", "account is disabled")
		return
	}
	s.startSession(w, r, u, http.StatusOK)
}

// newSessionFor persists a fresh session for u and returns it with a new
// CSRF token.
func (s *Server) newSessionFor(r *http.Request, u *domain.User) (*domain.Session, string, error) {
	now := time.Now().UTC()
	sess := &domain.Session{
		Token:       auth.NewToken(),
		UserID:      u.ID,
		CreatedAt:   now,
		ExpiresAt:   now.Add(domain.SessionTTL),
		RefreshedAt: now,
		IP:          ClientIP(r.Context()).String(),
		UA:          r.UserAgent(),
	}
	if err := s.store.CreateSession(r.Context(), sess); err != nil {
		return nil, "", err
	}
	if err := s.store.TouchLastSeen(r.Context(), u.ID); err != nil {
		s.log.Warn("touch lastSeenAt", "err", err)
	}
	s.metrics.Inc("auth_logins_total", 1)
	return sess, auth.NewToken(), nil
}

// startSession mints session + CSRF cookies and writes the login response.
func (s *Server) startSession(w http.ResponseWriter, r *http.Request, u *domain.User, status int) {
	sess, csrf, err := s.newSessionFor(r, u)
	if err != nil {
		s.internalError(w, r, "create session", err)
		return
	}
	s.setAuthCookies(w, sess.Token, csrf)
	writeJSON(w, status, map[string]any{
		"user":               u,
		"mustChangePassword": u.MustChangePassword(),
	})
}

func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
	if err := s.store.DeleteSession(r.Context(), CurrentSession(r.Context()).Token); err != nil {
		s.internalError(w, r, "delete session", err)
		return
	}
	s.clearAuthCookies(w)
	w.WriteHeader(http.StatusNoContent)
}

func (s *Server) handleLogoutAll(w http.ResponseWriter, r *http.Request) {
	n, err := s.store.DeleteUserSessions(r.Context(), CurrentUser(r.Context()).ID)
	if err != nil {
		s.internalError(w, r, "delete sessions", err)
		return
	}
	s.clearAuthCookies(w)
	writeJSON(w, http.StatusOK, map[string]any{"revoked": n})
}

func (s *Server) handleChangePassword(w http.ResponseWriter, r *http.Request) {
	var req struct {
		CurrentPassword string `json:"currentPassword"`
		NewPassword     string `json:"newPassword"`
	}
	if !decodeJSON(w, r, &req) {
		return
	}
	u := CurrentUser(r.Context())
	if u.Auth.Local == nil {
		writeError(w, http.StatusBadRequest, "no_local_auth",
			"this account signs in via SSO and has no password")
		return
	}
	if len(req.NewPassword) < auth.MinPasswordLen {
		writeError(w, http.StatusBadRequest, "weak_password",
			fmt.Sprintf("password must be at least %d characters", auth.MinPasswordLen))
		return
	}
	ok, err := auth.VerifyPassword(req.CurrentPassword, u.Auth.Local.PasswordHash)
	if err != nil {
		s.internalError(w, r, "verify password", err)
		return
	}
	if !ok {
		writeError(w, http.StatusUnauthorized, "invalid_credentials", "current password is incorrect")
		return
	}
	hash, err := auth.HashPassword(req.NewPassword)
	if err != nil {
		s.internalError(w, r, "hash password", err)
		return
	}
	if err := s.store.SetPassword(r.Context(), u.ID, hash, false); err != nil {
		s.internalError(w, r, "set password", err)
		return
	}
	// Revoke every other session: a password change is the recovery action
	// after credential leak.
	if _, err := s.store.DeleteUserSessionsExcept(r.Context(), u.ID, CurrentSession(r.Context()).Token); err != nil {
		s.log.Warn("revoke other sessions", "err", err)
	}
	w.WriteHeader(http.StatusNoContent)
}

func (s *Server) handleMe(w http.ResponseWriter, r *http.Request) {
	u := CurrentUser(r.Context())
	writeJSON(w, http.StatusOK, map[string]any{
		"user":               u,
		"mustChangePassword": u.MustChangePassword(),
		"oidcEnabled":        s.cfg.OIDC.Enabled(),
	})
}
