package provision

import (
	"bytes"
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestDecodeProvisionBodyAuthentikPayload(t *testing.T) {
	body := []byte(`{
		"email": "alice@ultisuite.fr",
		"password": "secret",
		"name": "Alice",
		"external_id": "uuid-123",
		"user": {"email": "ignored@example.com", "uuid": "ignored"}
	}`)
	req := httptest.NewRequest(http.MethodPost, "/internal/provision/user", bytes.NewReader(body))
	got, err := decodeProvisionBody(req)
	if err != nil {
		t.Fatalf("decodeProvisionBody() error = %v", err)
	}
	if got.Email != "alice@ultisuite.fr" || got.ExternalID != "uuid-123" || got.Name != "Alice" {
		t.Fatalf("decodeProvisionBody() = %#v", got)
	}
}

func TestAuthorizeProvisionSecret(t *testing.T) {
	req := httptest.NewRequest(http.MethodPost, "/internal/provision/user", nil)
	req.Header.Set("X-Provision-Secret", "topsecret")
	if !authorizeProvision(req, "topsecret") {
		t.Fatal("expected header secret to authorize")
	}
	req = httptest.NewRequest(http.MethodPost, "/internal/provision/user?secret=topsecret", nil)
	if !authorizeProvision(req, "topsecret") {
		t.Fatal("expected query secret to authorize")
	}
	if authorizeProvision(req, "wrong") {
		t.Fatal("expected wrong secret to fail")
	}
}

func TestNormalizeProvisionRequestUsesUsername(t *testing.T) {
	req := provisionUserRequest{Username: "bob@ultisuite.fr"}
	normalizeProvisionRequest(&req)
	if req.Email != "bob@ultisuite.fr" {
		t.Fatalf("email = %q, want bob@ultisuite.fr", req.Email)
	}
	if req.Name != "bob@ultisuite.fr" {
		t.Fatalf("name = %q, want fallback to email", req.Name)
	}
}
