package handlers

import (
	"log"
	"net/http"
	"strconv"

	"tankstopp/internal/auth"
	"tankstopp/internal/database"

	"github.com/gorilla/mux"
)

// Handler contains dependencies for all HTTP handlers
type Handler struct {
	db             *database.DB
	sessionManager *auth.SessionManager
}

// NewHandler creates a new handler with database connection and session manager
func NewHandler(db *database.DB) *Handler {
	return &Handler{
		db:             db,
		sessionManager: auth.NewSessionManager(),
	}
}

// AuthMiddleware checks if user is authenticated
func (h *Handler) AuthMiddleware(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		sessionID, err := auth.GetSessionCookie(r)
		if err != nil {
			http.Redirect(w, r, "/login", http.StatusSeeOther)
			return
		}

		session, exists := h.sessionManager.GetSession(sessionID)
		if !exists {
			http.Redirect(w, r, "/login", http.StatusSeeOther)
			return
		}

		// Add user info to request context
		r.Header.Set("X-User-ID", strconv.Itoa(int(session.UserID)))
		r.Header.Set("X-Username", session.Username)

		next.ServeHTTP(w, r)
	}
}

// getCurrentUser extracts user information from request headers
func (h *Handler) getCurrentUser(r *http.Request) (uint, string) {
	userIDStr := r.Header.Get("X-User-ID")
	username := r.Header.Get("X-Username")

	if userIDStr == "" {
		return 0, ""
	}

	userIDInt, err := strconv.Atoi(userIDStr)
	if err != nil {
		log.Printf("Error parsing user ID: %v", err)
		return 0, ""
	}

	return uint(userIDInt), username
}

// RegisterRoutes registers all application routes
func (h *Handler) RegisterRoutes(r *mux.Router) {
	// Static files
	r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))

	// Public routes (no authentication required)
	r.HandleFunc("/", h.RootHandler).Methods("GET")
	r.HandleFunc("/login", h.LoginHandler).Methods("GET", "POST")
	r.HandleFunc("/register", h.RegisterHandler).Methods("GET", "POST")
	r.HandleFunc("/logout", h.LogoutHandler).Methods("POST")

	// Protected routes (authentication required)
	r.HandleFunc("/dashboard", h.AuthMiddleware(h.HomeHandler)).Methods("GET")
	r.HandleFunc("/add", h.AuthMiddleware(h.AddFuelStopHandler)).Methods("GET", "POST")
	r.HandleFunc("/edit/{id:[0-9]+}", h.AuthMiddleware(h.EditFuelStopHandler)).Methods("GET", "POST")
	r.HandleFunc("/delete/{id:[0-9]+}", h.AuthMiddleware(h.DeleteFuelStopHandler)).Methods("POST")
	r.HandleFunc("/settings", h.AuthMiddleware(h.SettingsHandler)).Methods("GET")
	r.HandleFunc("/settings/profile", h.AuthMiddleware(h.UpdateProfileHandler)).Methods("POST")
	r.HandleFunc("/settings/password", h.AuthMiddleware(h.UpdatePasswordHandler)).Methods("POST")
	r.HandleFunc("/settings/delete-account", h.AuthMiddleware(h.DeleteAccountHandler)).Methods("POST")

	// Vehicle management routes
	r.HandleFunc("/vehicles", h.AuthMiddleware(h.VehiclesHandler)).Methods("GET")
	r.HandleFunc("/vehicles/add", h.AuthMiddleware(h.AddVehicleHandler)).Methods("GET", "POST")
	r.HandleFunc("/vehicles/edit/{id:[0-9]+}", h.AuthMiddleware(h.EditVehicleHandler)).Methods("GET", "POST")
	r.HandleFunc("/vehicles/delete/{id:[0-9]+}", h.AuthMiddleware(h.DeleteVehicleHandler)).Methods("POST")

	// API routes
	r.HandleFunc("/api/fuel-stops", h.AuthMiddleware(h.APIGetFuelStopsHandler)).Methods("GET")
	r.HandleFunc("/api/fuel-stops", h.AuthMiddleware(h.APICreateFuelStopHandler)).Methods("POST")
	r.HandleFunc("/api/stats", h.AuthMiddleware(h.APIGetFuelStopStatsHandler)).Methods("GET")
	r.HandleFunc("/api/vehicles/{id:[0-9]+}", h.AuthMiddleware(h.APIGetVehicleHandler)).Methods("GET")
}
