package Messages_test

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"net/http"
	"testing"

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

func createConversation(key Seeder.AesKey) (Models.ConversationDetail, Models.UserConversation, Models.ConversationDetailUser, error) {
	var (
		cd  Models.ConversationDetail
		uc  Models.UserConversation
		cdu Models.ConversationDetailUser
	)

	u, err := Database.GetUserByUsername("test")

	nameCiphertext, err := key.AesEncrypt([]byte("Test conversation"))
	if err != nil {
		return cd, uc, cdu, err
	}

	twoUserCiphertext, err := key.AesEncrypt([]byte("false"))
	if err != nil {
		return cd, uc, cdu, err
	}

	cd = Models.ConversationDetail{
		Name:    base64.StdEncoding.EncodeToString(nameCiphertext),
		TwoUser: base64.StdEncoding.EncodeToString(twoUserCiphertext),
	}

	err = Database.CreateConversationDetail(&cd)
	if err != nil {
		return cd, uc, cdu, err
	}

	conversationDetailIDCiphertext, err := key.AesEncrypt([]byte(cd.ID.String()))
	if err != nil {
		return cd, uc, cdu, err
	}

	adminCiphertext, err := key.AesEncrypt([]byte("true"))
	if err != nil {
		return cd, uc, cdu, err
	}

	pubKey := Seeder.GetPubKey()

	uc = Models.UserConversation{
		UserID:               u.ID,
		ConversationDetailID: base64.StdEncoding.EncodeToString(conversationDetailIDCiphertext),
		Admin:                base64.StdEncoding.EncodeToString(adminCiphertext),
		SymmetricKey: base64.StdEncoding.EncodeToString(
			Seeder.EncryptWithPublicKey(key.Key, pubKey),
		),
	}

	err = Database.CreateUserConversation(&uc)
	if err != nil {
		return cd, uc, cdu, err
	}

	userIDCiphertext, err := key.AesEncrypt([]byte(u.ID.String()))
	if err != nil {
		return cd, uc, cdu, err
	}

	usernameCiphertext, err := key.AesEncrypt([]byte(u.Username))
	if err != nil {
		return cd, uc, cdu, err
	}

	adminCiphertext, err = key.AesEncrypt([]byte("true"))
	if err != nil {
		return cd, uc, cdu, err
	}

	associationKeyCiphertext, err := key.AesEncrypt([]byte("association"))
	if err != nil {
		return cd, uc, cdu, err
	}

	publicKeyCiphertext, err := key.AesEncrypt([]byte(u.AsymmetricPublicKey))
	if err != nil {
		return cd, uc, cdu, err
	}

	cdu = Models.ConversationDetailUser{
		ConversationDetailID: cd.ID,
		UserID:               base64.StdEncoding.EncodeToString(userIDCiphertext),
		Username:             base64.StdEncoding.EncodeToString(usernameCiphertext),
		Admin:                base64.StdEncoding.EncodeToString(adminCiphertext),
		AssociationKey:       base64.StdEncoding.EncodeToString(associationKeyCiphertext),
		PublicKey:            base64.StdEncoding.EncodeToString(publicKeyCiphertext),
	}

	err = Database.CreateConversationDetailUser(&cdu)
	return cd, uc, cdu, err
}

func Test_UpdateConversation(t *testing.T) {
	client, ts, err := Tests.InitTestEnv()
	if err != nil {
		t.Errorf("Expected nil, recieved %s", err.Error())
		return
	}

	// u, err := Database.GetUserByUsername("test")

	key, err := Seeder.GenerateAesKey()
	if err != nil {
		t.Errorf("Expected nil, recieved %s", err.Error())
		return
	}

	cd, uc, cdu, err := createConversation(key)

	nameCiphertext, err := key.AesEncrypt([]byte("Not test conversation"))
	if err != nil {
		t.Errorf("Expected nil, recieved %s", err.Error())
	}

	d := struct {
		ID                string `json:"id"`
		Name              string `json:"name"`
		Users             []Models.ConversationDetailUser
		UserConversations []Models.UserConversation
	}{
		ID:   cd.ID.String(),
		Name: base64.StdEncoding.EncodeToString(nameCiphertext),
		Users: []Models.ConversationDetailUser{
			cdu,
		},
		UserConversations: []Models.UserConversation{
			uc,
		},
	}

	jsonStr, _ := json.Marshal(d)
	req, _ := http.NewRequest("PUT", ts.URL+"/api/v1/auth/conversations", bytes.NewBuffer(jsonStr))
	req.Header.Set("Content-Type", "application/json")

	resp, err := client.Do(req)
	if err != nil {
		t.Errorf("Expected nil, recieved %s", err.Error())
		return
	}

	if resp.StatusCode != http.StatusNoContent {
		t.Errorf("Expected %d, recieved %d", http.StatusNoContent, resp.StatusCode)
	}

	var ncd Models.ConversationDetail
	err = Database.DB.First(&ncd, "id = ?", cd.ID.String()).Error
	if err != nil {
		t.Errorf("Expected nil, recieved %s", err.Error())
		return
	}

	decodedName, err := base64.StdEncoding.DecodeString(ncd.Name)
	if err != nil {
		t.Errorf("Expected nil, recieved %s", err.Error())
		return
	}
	decrypedName, err := key.AesDecrypt(decodedName)
	if err != nil {
		t.Errorf("Expected %d, recieved %d", http.StatusOK, resp.StatusCode)
		return
	}

	if string(decrypedName) != "Not test conversation" {
		t.Errorf("Expected %s, recieved %s", "Not test converation", string(decrypedName))
	}

}
