package api

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

	"github.com/ponzischeme89/memby/server/internal/appupdate"
	"github.com/ponzischeme89/memby/server/internal/config"
	"github.com/ponzischeme89/memby/server/internal/store"
)

func TestUpdateStatusIsPublicAndAvailableDuringMaintenance(t *testing.T) {
	server := testServer(config.Config{})
	server.updatePolicy.set(appupdate.Policy{
		Enabled:        true,
		LatestVersion:  "0.3.0",
		MinimumVersion: "0.2.9",
		DownloadURL:    "/updates/memby-0.3.0.apk?token=signed",
	})
	server.maintenance.set(store.Maintenance{Enabled: true, Message: "Deploying"})

	req := httptest.NewRequest(http.MethodGet, "/v1/update", nil)
	req.Header.Set("X-Memby-Version", "0.2.8")
	rec := httptest.NewRecorder()
	// Deliberately no Authorization header: update policy must precede login.
	server.Routes().ServeHTTP(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200; body = %s", rec.Code, rec.Body.String())
	}
	var decision appupdate.Decision
	if err := json.Unmarshal(rec.Body.Bytes(), &decision); err != nil {
		t.Fatalf("decode decision: %v", err)
	}
	if decision.Status != appupdate.StatusMandatory {
		t.Fatalf("status = %q, want mandatory", decision.Status)
	}
}
