package Messages

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

	"git.tovijaeschke.xyz/tovi/Capsule/Backend/Database"
	"git.tovijaeschke.xyz/tovi/Capsule/Backend/Models"
	"github.com/gorilla/mux"
)

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

// ChangeUserMessageExpiry handles changing default message expiry for user
func ChangeConversationMessageExpiry(w http.ResponseWriter, r *http.Request) {
	var (
		// user                Models.User
		changeMessageExpiry rawChangeMessageExpiry
		conversationDetail  Models.ConversationDetail
		requestBody         []byte
		urlVars             map[string]string
		detailID            string
		ok                  bool
		err                 error
	)

	urlVars = mux.Vars(r)
	detailID, ok = urlVars["detailID"]
	if !ok {
		http.Error(w, "Not Found", http.StatusNotFound)
		return
	}

	conversationDetail, err = Database.GetConversationDetailByID(detailID)
	if err != nil {
		http.Error(w, "Not Found", http.StatusNotFound)
		return
	}

	// Ignore error here, as middleware should handle auth
	// TODO: Check if user in conversation
	// user, _ = Auth.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 = conversationDetail.MessageExpiryDefault.Scan(changeMessageExpiry.MessageExpiry)
	if err != nil {
		http.Error(w, "Error", http.StatusUnprocessableEntity)
		return
	}

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

	w.WriteHeader(http.StatusNoContent)
}
