package Auth_test

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"net/http"
	"os"
	"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 Test_AddProfileImage(t *testing.T) {
	client, ts, err := Tests.InitTestEnv()
	defer ts.Close()
	if err != nil {
		t.Errorf("Expected nil, recieved %s", err.Error())
		return
	}

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

	dat, err := os.ReadFile("./profile_picture_test.png")
	if err != nil {
		t.Errorf("Expected nil, recieved %s", err.Error())
		return
	}

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

	a := Models.Attachment{
		Mimetype:  "image/png",
		Extension: "png",
		Data:      base64.StdEncoding.EncodeToString(encDat),
	}

	jsonStr, _ := json.Marshal(a)
	req, _ := http.NewRequest("POST", ts.URL+"/api/v1/auth/image", 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)
		return
	}

	u, err := Database.GetUserByUsername("test")
	if err != nil {
		t.Errorf("Expected nil, recieved %s", err.Error())
		return
	}

	if u.AttachmentID.IsNil() {
		t.Errorf("Attachment not assigned to user")
	}

	err = os.Remove("/app/attachments/" + u.Attachment.FilePath)
	if err != nil {
		t.Errorf("Expected nil, recieved %s", err.Error())
		return
	}
}
