package Auth_test

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

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

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

	d := struct {
		MessageExpiry string `json:"message_expiry"`
	}{
		MessageExpiry: "fifteen_min",
	}

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

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

	if u.MessageExpiryDefault.String() != "fifteen_min" {
		t.Errorf("Failed to verify the MessageExpiryDefault has been changed")
	}
}

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

	d := struct {
		MessageExpiry string `json:"message_expiry"`
	}{
		MessageExpiry: "invalid_message_expiry",
	}

	jsonStr, _ := json.Marshal(d)
	req, _ := http.NewRequest("POST", ts.URL+"/api/v1/auth/message_expiry", 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.StatusUnprocessableEntity {
		t.Errorf("Expected %d, recieved %d", http.StatusUnprocessableEntity, resp.StatusCode)
	}

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

	if u.MessageExpiryDefault.String() != "no_expiry" {
		t.Errorf("Failed to verify the MessageExpiryDefault has not been changed")
	}
}
