package Messages

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

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

type rawMessageData struct {
	MessageData Models.MessageData `json:"message_data"`
	Messages    []Models.Message   `json:"message"`
}

// CreateMessage sends a message
func CreateMessage(w http.ResponseWriter, r *http.Request) {
	var (
		messagesData []rawMessageData
		messageData  rawMessageData
		message      Models.Message
		t            time.Time
		decodedFile  []byte
		fileName     string
		i            int
		err          error
	)

	err = json.NewDecoder(r.Body).Decode(&messagesData)
	if err != nil {
		http.Error(w, "Error", http.StatusInternalServerError)
		return
	}

	for _, messageData = range messagesData {
		if messageData.MessageData.Data == "" {
			decodedFile, err = base64.StdEncoding.DecodeString(messageData.MessageData.Attachment.Data)
			fileName, err = Util.WriteFile(decodedFile)
			messageData.MessageData.Attachment.FilePath = fileName
		}

		for i, message = range messageData.Messages {
			t, err = time.Parse("2006-01-02T15:04:05Z", message.ExpiryRaw)
			if err == nil {
				err = messageData.Messages[i].Expiry.Scan(t)
				if err != nil {
					http.Error(w, "Error", http.StatusInternalServerError)
					return
				}
			}
		}

		err = Database.CreateMessageData(&messageData.MessageData)
		if err != nil {
			http.Error(w, "Error", http.StatusInternalServerError)
			return
		}

		err = Database.CreateMessages(&messageData.Messages)
		if err != nil {
			http.Error(w, "Error", http.StatusInternalServerError)
			return
		}
	}

	w.WriteHeader(http.StatusNoContent)
}
