package Users

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

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

// SearchUsers searches a for a user by username
func SearchUsers(w http.ResponseWriter, r *http.Request) {
	var (
		user        Models.User
		query       url.Values
		rawUsername []string
		username    string
		returnJSON  []byte
		ok          bool
		err         error
	)

	query = r.URL.Query()
	rawUsername, ok = query["username"]
	if !ok {
		http.Error(w, "Not Found", http.StatusNotFound)
		return
	}

	if len(rawUsername) != 1 {
		http.Error(w, "Not Found", http.StatusNotFound)
		return
	}

	username = rawUsername[0]

	user, err = Database.GetUserByUsername(username)
	if err != nil {
		http.Error(w, "Not Found", http.StatusNotFound)
		return
	}

	user.Password = ""
	user.AsymmetricPrivateKey = ""

	returnJSON, err = json.MarshalIndent(user, "", "  ")
	if err != nil {
		http.Error(w, "Not Found", http.StatusNotFound)
		return
	}

	w.WriteHeader(http.StatusOK)
	w.Write(returnJSON)
}
