package handler

import (
	"fmt"
	"net/http"
	"portfolio-tracker/internal/model" // Add this import
	"portfolio-tracker/internal/session"

	"golang.org/x/crypto/bcrypt"
)

func RegisterHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Nur POST erlaubt", http.StatusMethodNotAllowed)
		return
	}

	username := r.FormValue("username")
	email := r.FormValue("email")
	password := r.FormValue("password")

	if username == "" || email == "" || password == "" {
		http.Error(w, "Alle Felder sind erforderlich", http.StatusBadRequest)
		return
	}

	// Passwort hashen
	hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		http.Error(w, "Fehler beim Hashen des Passworts", http.StatusInternalServerError)
		return
	}

	user := model.User{
		Username: username,
		Email:    email,
		Password: string(hash),
	}

	if err := DB.Create(&user).Error; err != nil {
		http.Error(w, "Fehler beim Speichern des Users: "+err.Error(), http.StatusInternalServerError)
		return
	}

	http.Redirect(w, r, "/", http.StatusSeeOther)
}

func LoginHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Nur POST erlaubt", http.StatusMethodNotAllowed)
		return
	}

	username := r.FormValue("username")
	password := r.FormValue("password")

	if username == "" || password == "" {
		http.Error(w, "Alle Felder sind erforderlich", http.StatusBadRequest)
		return
	}

	var user model.User
	if err := DB.Where("username = ?", username).First(&user).Error; err != nil {
		http.Error(w, "Benutzer nicht gefunden", http.StatusUnauthorized)
		return
	}

	// Passwort prüfen
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
		http.Error(w, "Falsches Passwort", http.StatusUnauthorized)
		return
	}

	// Session erstellen oder abrufen
	session, err := session.Store.Get(r, "hnrx_pft_session")
	if err != nil {
		fmt.Printf("Error getting session: %v\n", err)
		http.Error(w, "Session-Fehler", http.StatusInternalServerError)
		return
	}

	// Session-Werte setzen
	session.Values["authenticated"] = true
	session.Values["username"] = username

	// Debug output
	fmt.Printf("Setting session values - Auth: %v, Username: %s\n", true, username)
	fmt.Printf("Session ID before save: %s\n", session.ID)

	// Session speichern
	err = session.Save(r, w)
	if err != nil {
		fmt.Printf("Error saving session: %v\n", err)
		http.Error(w, "Fehler beim Speichern der Session", http.StatusInternalServerError)
		return
	}

	fmt.Printf("Session saved successfully with ID: %s\n", session.ID)
	http.Redirect(w, r, "/", http.StatusSeeOther)
}

func LogoutHandler(w http.ResponseWriter, r *http.Request) {
	session, err := session.Store.Get(r, "hnrx_pft_session")
	if err != nil {
		fmt.Printf("Error getting session in logout: %v\n", err)
		// Continue with logout even if session retrieval fails
	}

	// Clear session values
	session.Values["authenticated"] = false
	session.Values["username"] = ""

	// Set session options to delete the session
	session.Options.MaxAge = -1

	// Save the session (this will delete it due to MaxAge = -1)
	err = session.Save(r, w)
	if err != nil {
		fmt.Printf("Error saving session during logout: %v\n", err)
		http.Error(w, "Fehler beim Logout", http.StatusInternalServerError)
		return
	}

	fmt.Printf("Session successfully logged out\n")
	http.Redirect(w, r, "/", http.StatusSeeOther)
}
