package httpserver

import (
	"bufio"
	"fmt"
	"net"
	"net/http"
	"strings"
	"time"

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

	"github.com/tim/cairnquire/apps/server/internal/auth"
)

const devLogoutCookieName = "cairnquire_dev_logout"

func (s *Server) timeoutExceptWebSocket(timeout time.Duration) func(http.Handler) http.Handler {
	timeoutMiddleware := middleware.Timeout(timeout)
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if r.URL.Path == "/ws" {
				next.ServeHTTP(w, r)
				return
			}
			timeoutMiddleware(next).ServeHTTP(w, r)
		})
	}
}

func (s *Server) requestLogger(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ww := &statusWriter{ResponseWriter: w, status: http.StatusOK}
		start := time.Now()
		next.ServeHTTP(ww, r)
		s.logger.Info("http request",
			"method", r.Method,
			"path", r.URL.Path,
			"status", ww.status,
			"duration", time.Since(start).String(),
		)
	})
}

func (s *Server) securityHeaders(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Security-Policy", "default-src 'self'; base-uri 'self'; frame-ancestors 'none'; img-src 'self' data:; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; script-src 'self' https://cdn.jsdelivr.net; font-src 'self' https://cdn.jsdelivr.net; connect-src 'self' ws: wss:; object-src 'none'")
		w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
		w.Header().Set("X-Content-Type-Options", "nosniff")
		w.Header().Set("X-Frame-Options", "DENY")
		w.Header().Set("Cross-Origin-Opener-Policy", "same-origin")
		w.Header().Set("Cross-Origin-Resource-Policy", "same-origin")
		next.ServeHTTP(w, r)
	})
}

func (s *Server) authMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		principal, ok := s.authenticateRequest(r)
		if ok {
			r = r.WithContext(withPrincipal(r.Context(), principal))
		}

		required, protected := requiredScopeForPath(r)
		if !protected {
			next.ServeHTTP(w, r)
			return
		}
		if !ok {
			if r.Method == http.MethodGet && !strings.HasPrefix(r.URL.Path, "/api/") {
				http.Redirect(w, r, "/login?next="+urlQueryEscape(r.URL.RequestURI()), http.StatusSeeOther)
				return
			}
			writeJSONWithStatus(w, http.StatusUnauthorized, map[string]string{"error": "authentication required"})
			return
		}
		if !allowsProtectedRoute(principal, required) {
			writeJSONWithStatus(w, http.StatusForbidden, map[string]string{"error": "forbidden"})
			return
		}
		next.ServeHTTP(w, r)
	})
}

func allowsProtectedRoute(principal auth.Principal, required auth.Scope) bool {
	if required == auth.ScopeAdmin {
		return auth.Allows(principal, required)
	}
	if len(principal.Scopes) > 0 {
		return auth.HasScope(principal.Scopes, required)
	}
	return principal.UserID != ""
}

func urlQueryEscape(value string) string {
	return strings.NewReplacer("%", "%25", " ", "%20", "?", "%3F", "&", "%26", "=", "%3D", "#", "%23").Replace(value)
}

func (s *Server) setupMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		settings, err := s.auth.GetInstanceSettings(r.Context())
		if err != nil {
			writeJSONWithStatus(w, http.StatusInternalServerError, map[string]string{"error": "lookup initial setup state"})
			return
		}
		if settings.SetupComplete || isSetupAllowedPath(r.URL.Path) {
			next.ServeHTTP(w, r)
			return
		}
		if r.Method == http.MethodGet && !strings.HasPrefix(r.URL.Path, "/api/") {
			http.Redirect(w, r, "/setup", http.StatusSeeOther)
			return
		}
		writeJSONWithStatus(w, http.StatusServiceUnavailable, map[string]string{"error": "initial setup is required"})
	})
}

func isSetupAllowedPath(path string) bool {
	return path == "/setup" ||
		path == "/api/setup" ||
		path == "/health" ||
		path == "/healthz" ||
		path == "/readyz" ||
		path == "/sw.js" ||
		strings.HasPrefix(path, "/static/")
}

func (s *Server) authenticateRequest(r *http.Request) (auth.Principal, bool) {
	var token string
	if header := r.Header.Get("Authorization"); strings.HasPrefix(header, "Bearer ") {
		token = strings.TrimSpace(strings.TrimPrefix(header, "Bearer "))
	} else if r.URL.Path == "/ws" {
		token = r.URL.Query().Get("token")
	}

	if token != "" {
		if s.config.DevMode && token == "dev" {
			principal, err := s.auth.PrincipalForUser(r.Context(), s.devUserID)
			return principal, err == nil
		}
		principal, err := s.auth.ValidateBearerToken(r.Context(), token)
		if err == nil {
			return principal, true
		}
		s.logger.Warn("invalid bearer token", "error", err)
		return auth.Principal{}, false
	}
	cookie, err := r.Cookie(auth.SessionCookieName)
	if err != nil || cookie.Value == "" {
		if s.devUserID == "" || hasDevLogoutCookie(r) {
			return auth.Principal{}, false
		}
		principal, err := s.auth.PrincipalForUser(r.Context(), s.devUserID)
		return principal, err == nil
	}
	principal, err := s.auth.ValidateSessionToken(r.Context(), cookie.Value)
	if err != nil {
		return auth.Principal{}, false
	}
	return principal, true
}

func hasDevLogoutCookie(r *http.Request) bool {
	cookie, err := r.Cookie(devLogoutCookieName)
	return err == nil && cookie.Value == "1"
}

func requiredScopeForPath(r *http.Request) (auth.Scope, bool) {
	path := r.URL.Path
	method := r.Method
	switch {
	case path == "/" || (path == "/permissions" && method == http.MethodGet):
		return auth.ScopeDocsRead, true
	case path == "/permissions" && method == http.MethodPost:
		return auth.ScopeDocsWrite, true
	case strings.HasPrefix(path, "/api/auth/"):
		if path == "/api/auth/me" || path == "/api/auth/logout" || path == "/api/auth/password/change" || path == "/api/auth/account" || strings.HasPrefix(path, "/api/auth/passkeys/me/") {
			return auth.ScopeDocsRead, true
		}
		return "", false
	case strings.HasPrefix(path, "/api/device/"):
		if path == "/api/device/approve" || path == "/api/device/verify" {
			return auth.ScopeDocsRead, true
		}
		return "", false
	case strings.HasPrefix(path, "/api/tokens"):
		return auth.ScopeDocsRead, true
	case path == "/ws":
		return auth.ScopeDocsRead, true
	case strings.HasPrefix(path, "/api/admin/"):
		return auth.ScopeAdmin, true
	case strings.HasPrefix(path, "/api/documents/") && method != http.MethodGet:
		return auth.ScopeDocsWrite, true
	case path == "/api/documents" || path == "/api/search" || (path == "/api/permissions" && method == http.MethodGet):
		return auth.ScopeDocsRead, true
	case path == "/api/permissions" && method == http.MethodPatch:
		return auth.ScopeDocsWrite, true
	case strings.HasPrefix(path, "/api/uploads"):
		return auth.ScopeDocsWrite, true
	case path == "/api/attachments":
		return auth.ScopeDocsRead, true
	case strings.HasPrefix(path, "/api/sync/"):
		if method == http.MethodPost {
			return auth.ScopeSyncWrite, true
		}
		return auth.ScopeSyncRead, true
	case strings.HasPrefix(path, "/api/content/"):
		return auth.ScopeSyncRead, true
	case strings.HasPrefix(path, "/api/comments"):
		if method == http.MethodGet {
			return auth.ScopeDocsRead, true
		}
		return auth.ScopeDocsWrite, true
	case strings.HasPrefix(path, "/api/notifications"):
		return auth.ScopeDocsRead, true
	case strings.HasPrefix(path, "/api/watch"):
		return auth.ScopeDocsRead, true
	case path == "/docs" || strings.HasPrefix(path, "/docs/"):
		return auth.ScopeDocsRead, true
	case strings.HasSuffix(path, "/edit"):
		return auth.ScopeDocsWrite, true
	default:
		return "", false
	}
}

type statusWriter struct {
	http.ResponseWriter
	status int
}

func (w *statusWriter) WriteHeader(status int) {
	w.status = status
	w.ResponseWriter.WriteHeader(status)
}

func (w *statusWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
	hijacker, ok := w.ResponseWriter.(http.Hijacker)
	if !ok {
		return nil, nil, fmt.Errorf("response writer does not support hijacking")
	}
	return hijacker.Hijack()
}
