package handlers

import (
	"html/template"
	"net/http"
	"minecraft-profile/middleware"
	"minecraft-profile/models"
)

func RegisterHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		tmpl := template.Must(template.ParseFiles("templates/register.html"))
		tmpl.Execute(w, nil)
		return
	}

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

	if username == "" || password == "" || email == "" {
		http.Error(w, "All fields are required", http.StatusBadRequest)
		return
	}

	if _, exists := models.GetUser(username); exists {
		http.Error(w, "User already exists", http.StatusBadRequest)
		return
	}

	models.CreateUser(username, password, email)

	sessionValue := middleware.CreateSession(username, "user")
	http.SetCookie(w, &http.Cookie{
		Name:     "session",
		Value:    sessionValue,
		Path:     "/",
		HttpOnly: true,
		SameSite: http.SameSiteStrictMode,
	})

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

func LoginHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		tmpl := template.Must(template.ParseFiles("templates/login.html"))
		tmpl.Execute(w, nil)
		return
	}

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

	if !models.ValidateUser(username, password) {
		http.Error(w, "Invalid credentials", http.StatusUnauthorized)
		return
	}

	user, _ := models.GetUser(username)
	sessionValue := middleware.CreateSession(username, user.Role)
	http.SetCookie(w, &http.Cookie{
		Name:     "session",
		Value:    sessionValue,
		Path:     "/",
		HttpOnly: true,
		SameSite: http.SameSiteStrictMode,
	})

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

func LogoutHandler(w http.ResponseWriter, r *http.Request) {
	http.SetCookie(w, &http.Cookie{
		Name:   "session",
		Value:  "",
		Path:   "/",
		MaxAge: -1,
	})
	http.Redirect(w, r, "/", http.StatusSeeOther)
}
