package main

import "net/http"

func isMethodAllowed(response *http.ResponseWriter, request *http.Request) bool {
	if request.Method != http.MethodPost {
		http.Error(*response, "POST only", http.StatusMethodNotAllowed)
		return false
	}
	return true
}

func RegisterHandler(response http.ResponseWriter, request *http.Request) {
	if !isMethodAllowed(&response, request) {
		return
	}

	ctx := request.Context()

	username := request.FormValue("username")
	if len(username) < 4 {
		http.Error(response, "no or short username", http.StatusBadRequest)
		return
	}

	password := request.FormValue("password")
	if len(password) < 8 {
		http.Error(response, "no or short password", http.StatusBadRequest)
		return
	}

	newClient := Client{
		Name:         username,
		PasswordHash: password,
		Color:        [3]uint8{120, 120, 120}, //"xxx"
	}

	err := CreateClient(ctx, &newClient)
	if err != nil {
		http.Error(response, "taken", http.StatusBadRequest)
		return
	}
	response.Write([]byte("registered"))
}

func LoginHandler(response http.ResponseWriter, request *http.Request) {
	if !isMethodAllowed(&response, request) {
		return
	}

	ctx := request.Context()

	username := request.FormValue("username")
	if len(username) < 4 {
		http.Error(response, "no or short username", http.StatusBadRequest)
		return
	}

	password := request.FormValue("password")
	if len(password) < 8 {
		http.Error(response, "no or short password", http.StatusBadRequest)
		return
	}

	var client Client

	id, err := GetIdFromClientName(ctx, username)
	if err != nil {
		http.Error(response, "bad login", http.StatusBadRequest)
		return
	}

	err = DbGetClient(ctx)
	if err != nil {
		http.Error(response, "bad login", http.StatusBadRequest)
		return
	}

	token, err := GetToken(id)
	if err != nil {
		http.Error(response, "Internal error", http.StatusInternalServerError)
		return
	}

	response.Write([]byte(token))
}
