//go:build integration

package integrationtest

import (
	"encoding/json"
	"testing"
)

func TestHealthz(t *testing.T) {
	h := RequireHarness(t)
	resp, err := h.Server.Client().Get(h.Server.URL + "/healthz")
	if err != nil {
		t.Fatalf("GET /healthz: %v", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != 200 && resp.StatusCode != 503 {
		t.Fatalf("status = %d, want 200 or 503", resp.StatusCode)
	}

	var report map[string]any
	if err := json.NewDecoder(resp.Body).Decode(&report); err != nil {
		t.Fatalf("decode: %v", err)
	}
	if report["status"] == nil {
		t.Fatalf("missing status field: %#v", report)
	}
}

func TestUnauthorizedWithoutToken(t *testing.T) {
	h := RequireHarness(t)
	client := NewClient(h.Server.URL, "")
	resp, err := client.Get("/api/v1/mail/settings")
	if err != nil {
		t.Fatalf("GET: %v", err)
	}
	AssertErrorCode(t, resp, 401, "auth.missing_authorization")
}

func TestInvalidToken(t *testing.T) {
	h := RequireHarness(t)
	client := NewClient(h.Server.URL, "not-a-valid-jwt")
	resp, err := client.Get("/api/v1/mail/settings")
	if err != nil {
		t.Fatalf("GET: %v", err)
	}
	if resp.Status != 401 {
		t.Fatalf("status = %d, want 401; body = %s", resp.Status, string(resp.Body))
	}
}
