package server

import (
	"encoding/json"
	"errors"
	"net/http"
	"time"

	"github.com/go-chi/chi/v5"

	"github.com/operator/command-center/internal/auth"
)

// AuthDeps bundles the auth-related dependencies wired by main.go.
type AuthDeps struct {
	WebAuthn    *auth.WebAuthn
	Sessions    *auth.SessionStore
	Recovery    *auth.RecoveryStore
	Credentials *auth.CredentialStore
	Audit       *auth.AuditWriter
	LoginLimit  *auth.RateLimiter
	RecoveryLim *auth.RateLimiter
}

type registerFinishReq struct {
	DeviceName string `json:"device_name"`
}

type registerFinishResp struct {
	RecoveryCodes []string `json:"recovery_codes,omitempty"`
	DeviceID      string   `json:"device_id"`
}

func (s *Server) handleAuthStatus(w http.ResponseWriter, r *http.Request) {
	if s.auth == nil {
		http.Error(w, "auth not configured", http.StatusServiceUnavailable)
		return
	}
	n, err := s.auth.Credentials.Count(r.Context())
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	writeJSON(w, http.StatusOK, map[string]any{"registered": n > 0})
}

func (s *Server) handleAuthMe(w http.ResponseWriter, r *http.Request) {
	sess := auth.SessionFromContext(r.Context())
	if sess == nil {
		http.Error(w, "unauthorized", http.StatusUnauthorized)
		return
	}
	writeJSON(w, http.StatusOK, map[string]any{
		"created_at":    sess.CreatedAt.Unix(),
		"expires_at":    sess.ExpiresAt.Unix(),
		"last_seen_at":  sess.LastSeenAt.Unix(),
		"session_lifetime_seconds": int(s.auth.Sessions.Lifetime().Seconds()),
	})
}

func (s *Server) handleAuthLogout(w http.ResponseWriter, r *http.Request) {
	sess := auth.SessionFromContext(r.Context())
	if sess != nil {
		_ = s.auth.Sessions.Revoke(r.Context(), sess.Token)
		s.auth.Audit.Write(r.Context(), r, "operator", "logout", "session", "", nil)
	}
	s.auth.Sessions.ClearCookie(w)
	writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}

func (s *Server) handleWebAuthnRegisterStart(w http.ResponseWriter, r *http.Request) {
	if !s.allowBootstrapOrAuthed(r) {
		http.Error(w, "registration requires an active session once a credential exists", http.StatusUnauthorized)
		return
	}
	opts, err := s.auth.WebAuthn.BeginRegistration(r.Context(), w)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	_, _ = w.Write(opts)
}

func (s *Server) handleWebAuthnRegisterFinish(w http.ResponseWriter, r *http.Request) {
	if !s.allowBootstrapOrAuthed(r) {
		http.Error(w, "registration requires an active session once a credential exists", http.StatusUnauthorized)
		return
	}

	// Decode the optional device-name hint without consuming the body the
	// library re-parses: the JSON body the browser sends is the
	// PublicKeyCredentialCreationOptionsJSON shape; device_name comes as a
	// separate query string for simplicity.
	deviceName := r.URL.Query().Get("device_name")
	_ = registerFinishReq{} // documented type for the response below

	// First-credential bootstrap creates recovery codes.
	wasFirst := false
	if n, err := s.auth.Credentials.Count(r.Context()); err == nil && n == 0 {
		wasFirst = true
	}

	cred, err := s.auth.WebAuthn.FinishRegistration(r.Context(), r, deviceName)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	resp := registerFinishResp{DeviceID: base64URLEncode(cred.ID)}
	if wasFirst {
		codes, err := s.auth.Recovery.GenerateBatch(r.Context())
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		resp.RecoveryCodes = codes
	}

	// Issue a session immediately so registration → logged-in is one step.
	sess, err := s.auth.Sessions.Issue(r.Context(), r.Header.Get("User-Agent"), r.RemoteAddr)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	s.auth.Sessions.SetCookie(w, sess)

	s.auth.Audit.Write(r.Context(), r, "operator", "register_credential",
		"credential", resp.DeviceID, map[string]any{"first": wasFirst})

	writeJSON(w, http.StatusOK, resp)
}

func (s *Server) handleWebAuthnLoginStart(w http.ResponseWriter, r *http.Request) {
	key := auth.KeyForRoute("login_start", r)
	if !s.auth.LoginLimit.Allow(key) {
		http.Error(w, "rate limited", http.StatusTooManyRequests)
		return
	}
	opts, err := s.auth.WebAuthn.BeginLogin(r.Context(), w)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	_, _ = w.Write(opts)
}

func (s *Server) handleWebAuthnLoginFinish(w http.ResponseWriter, r *http.Request) {
	key := auth.KeyForRoute("login_finish", r)
	if !s.auth.LoginLimit.Allow(key) {
		http.Error(w, "rate limited", http.StatusTooManyRequests)
		return
	}
	cred, err := s.auth.WebAuthn.FinishLogin(r.Context(), r)
	if err != nil {
		s.auth.Audit.Write(r.Context(), r, "anonymous", "login_failed", "", "", map[string]any{"error": err.Error()})
		http.Error(w, err.Error(), http.StatusUnauthorized)
		return
	}
	sess, err := s.auth.Sessions.Issue(r.Context(), r.Header.Get("User-Agent"), r.RemoteAddr)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	s.auth.Sessions.SetCookie(w, sess)
	s.auth.Audit.Write(r.Context(), r, "operator", "login",
		"credential", base64URLEncode(cred.ID), nil)
	writeJSON(w, http.StatusOK, map[string]any{
		"ok":         true,
		"expires_at": sess.ExpiresAt.Unix(),
	})
}

type recoveryReq struct {
	Code string `json:"code"`
}

func (s *Server) handleRecovery(w http.ResponseWriter, r *http.Request) {
	key := auth.KeyForRoute("recovery", r)
	if !s.auth.RecoveryLim.Allow(key) {
		http.Error(w, "rate limited", http.StatusTooManyRequests)
		return
	}
	var body recoveryReq
	if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
		http.Error(w, "bad json", http.StatusBadRequest)
		return
	}
	if err := s.auth.Recovery.Redeem(r.Context(), body.Code); err != nil {
		s.auth.Audit.Write(r.Context(), r, "anonymous", "recovery_failed", "", "", nil)
		http.Error(w, "invalid recovery code", http.StatusUnauthorized)
		return
	}
	// Successful recovery clears all stored credentials so the operator must
	// re-enroll. This is consistent with the "I lost access to my devices"
	// recovery scenario the codes are designed for.
	creds, _ := s.auth.Credentials.List(r.Context())
	for _, c := range creds {
		_ = s.auth.Credentials.Delete(r.Context(), c.ID)
	}
	sess, err := s.auth.Sessions.Issue(r.Context(), r.Header.Get("User-Agent"), r.RemoteAddr)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	s.auth.Sessions.SetCookie(w, sess)
	s.auth.Audit.Write(r.Context(), r, "operator", "recovery_redeemed", "session", "", nil)
	writeJSON(w, http.StatusOK, map[string]any{
		"ok":      true,
		"message": "Recovery code accepted. Existing credentials cleared. Register a new device now.",
	})
}

func (s *Server) handleListDevices(w http.ResponseWriter, r *http.Request) {
	creds, err := s.auth.Credentials.List(r.Context())
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	writeJSON(w, http.StatusOK, map[string]any{
		"count":   len(creds),
		"devices": creds,
	})
}

func (s *Server) handleDeleteDevice(w http.ResponseWriter, r *http.Request) {
	id := chi.URLParam(r, "id")
	if id == "" {
		http.Error(w, "missing id", http.StatusBadRequest)
		return
	}
	n, err := s.auth.Credentials.Count(r.Context())
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if n <= 1 {
		http.Error(w, "cannot remove the last credential — register a replacement first", http.StatusConflict)
		return
	}
	if err := s.auth.Credentials.Delete(r.Context(), id); err != nil {
		if errors.Is(err, auth.ErrCredentialNotFound) {
			http.Error(w, "not found", http.StatusNotFound)
			return
		}
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	s.auth.Audit.Write(r.Context(), r, "operator", "delete_credential", "credential", id, nil)
	writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}

// allowBootstrapOrAuthed returns true when the request is allowed to perform
// the register ceremony: either a valid session exists, or no credentials
// have been registered yet.
func (s *Server) allowBootstrapOrAuthed(r *http.Request) bool {
	// If there's a valid session, the middleware would have stashed it —
	// but register/* are exempt from the middleware, so re-validate here.
	if sess, err := s.auth.Sessions.Validate(r.Context(), r); err == nil && sess != nil {
		return true
	}
	n, err := s.auth.Credentials.Count(r.Context())
	if err != nil {
		return false
	}
	return n == 0
}

func base64URLEncode(b []byte) string {
	// Local helper to avoid importing encoding/base64 from this file when
	// the credential.ID -> string conversion is the only need.
	return _b64.EncodeToString(b)
}

// suppress unused warnings if registerFinishReq becomes used in a later iteration.
var _ = registerFinishReq{}
var _ = time.Now
