package Auth

import (
	"encoding/json"
	"net/http"

	"git.tovijaeschke.xyz/tovi/Capsule/Backend/Database"
	"git.tovijaeschke.xyz/tovi/Capsule/Backend/Models"
)

type signup struct {
	Username        string `json:"username"`
	Password        string `json:"password"`
	ConfirmPassword string `json:"confirm_password"`
	PublicKey       string `json:"asymmetric_public_key"`
	PrivateKey      string `json:"asymmetric_private_key"`
	SymmetricKey    string `json:"symmetric_key"`
}

// Signup to the platform
func Signup(w http.ResponseWriter, r *http.Request) {
	var (
		user Models.User
		err  error
	)

	err = json.NewDecoder(r.Body).Decode(&user)
	if err != nil {
		http.Error(w, "Invalid Data", http.StatusUnprocessableEntity)
		return
	}

	if user.Username == "" ||
		user.Password == "" ||
		user.ConfirmPassword == "" ||
		len(user.AsymmetricPrivateKey) == 0 ||
		len(user.AsymmetricPublicKey) == 0 ||
		len(user.SymmetricKey) == 0 {

		http.Error(w, "Invalid Data", http.StatusUnprocessableEntity)
		return
	}

	if user.Password != user.ConfirmPassword {
		http.Error(w, "Invalid Data", http.StatusUnprocessableEntity)
		return
	}

	err = Database.CheckUniqueUsername(user.Username)
	if err != nil {
		http.Error(w, "Invalid Data", http.StatusUnprocessableEntity)
		return
	}

	user.Password, err = HashPassword(user.Password)
	if err != nil {
		http.Error(w, "Error", http.StatusInternalServerError)
		return
	}

	err = Database.CreateUser(&user)
	if err != nil {
		http.Error(w, "Error", http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}
