package handlers

import (
	"html/template"
	"mc-monitor/middleware"
	"mc-monitor/models"
	"net/http"
)

type AuthPageData struct {
	Error string
}

func RegisterHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == http.MethodGet {
		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)
	http.SetCookie(w, &http.Cookie{
		Name:     "session",
		Value:    sessionValue,
		Path:     "/",
		HttpOnly: true,
		SameSite: http.SameSiteStrictMode,
	})

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

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

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

	if !models.ValidateUser(username, password) {
		tmpl := template.Must(template.ParseFiles("templates/login.html"))
		tmpl.Execute(w, AuthPageData{Error: "Неверный логин или пароль"})
		return
	}

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

	http.Redirect(w, r, "/dashboard", 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)
}
