package main

import (
	"net/http"
	"net/http/httptest"
	"os"
	"path"
	"strings"
	"testing"
	"time"
)

func TestHTTPPostQuestionAnswers(t *testing.T) {
	p := path.Join(t.TempDir(), "db.yaml")
	os.WriteFile(p, []byte("{}"), os.ModePerm)
	db, err := newYamlDB(p)
	if err != nil {
		t.Fatal(err)
	}

	w := httptest.NewRecorder()
	r := httptest.NewRequest(
		http.MethodPost,
		"/api/questions/QID/answers",
		strings.NewReader(`{"answer":"a", "passed": false}`),
	)
	r.SetBasicAuth("u", "")

	withAuth(withDB(httpPostQuestionAnswers, db))(w, r)

	if w.Code != http.StatusOK {
		t.Error(w.Code)
	}

	_, got := db.LastAnswer("u", "QID")
	if got == (Answer{}) {
		t.Error("no answer pushed:", got)
	}
	if got.Q != "QID" {
		t.Error(got.Q)
	} else if got.A != "a" {
		t.Error(got.A)
	} else if time.Since(time.Unix(0, got.TS)) > time.Minute {
		t.Error(got.TS)
	} else if got.Author != "u" {
		t.Error(got.Author)
	} else if got.Pass != false {
		t.Error(got.Pass)
	}
}
