package Auth

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

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

type rawChangeMessageExpiry struct {
	MessageExpiry string `json:"message_expiry"`
}

// ChangeMessageExpiry handles changing default message expiry for user
func ChangeMessageExpiry(w http.ResponseWriter, r *http.Request) {
	var (
		user                Models.User
		changeMessageExpiry rawChangeMessageExpiry
		requestBody         []byte
		err                 error
	)

	// Ignore error here, as middleware should handle auth
	user, _ = CheckCookieCurrentUser(w, r)

	requestBody, err = ioutil.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "Error", http.StatusInternalServerError)
		return
	}

	err = json.Unmarshal(requestBody, &changeMessageExpiry)
	if err != nil {
		http.Error(w, "Error", http.StatusInternalServerError)
		return
	}

	err = user.MessageExpiryDefault.Scan(changeMessageExpiry.MessageExpiry)
	if err != nil {
		http.Error(w, "Error", http.StatusUnprocessableEntity)
		return
	}

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

	w.WriteHeader(http.StatusNoContent)
}
