package integration_test

import (
	"context"
	"encoding/json"
	"net/http"
	"testing"
	"time"

	"galaxy/integration/testenv"
)

// TestAdminFlow_BootstrapAndCRUD verifies that the bootstrap admin
// account can authenticate against backend's admin surface, create a
// second admin, and that the second admin can disable the first.
func TestAdminFlow_BootstrapAndCRUD(t *testing.T) {
	plat := testenv.Bootstrap(t, testenv.BootstrapOptions{})
	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
	defer cancel()

	bootstrap := testenv.NewBackendAdminClient(plat.Backend.HTTPURL, plat.Backend.AdminUser, plat.Backend.AdminPassword)

	// Create a second admin account.
	body := map[string]any{
		"username": "secondary",
		"password": "secondary-secret-pw",
	}
	raw, resp, err := bootstrap.Do(ctx, http.MethodPost, "/api/v1/admin/admin-accounts", body)
	if err != nil {
		t.Fatalf("create admin: %v", err)
	}
	if resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusOK {
		t.Fatalf("create admin: status %d body=%s", resp.StatusCode, string(raw))
	}

	// Switch to the secondary admin and disable the bootstrap admin.
	secondary := testenv.NewBackendAdminClient(plat.Backend.HTTPURL, "secondary", "secondary-secret-pw")
	raw, resp, err = secondary.Do(ctx, http.MethodPost, "/api/v1/admin/admin-accounts/"+plat.Backend.AdminUser+"/disable", nil)
	if err != nil {
		t.Fatalf("disable bootstrap: %v", err)
	}
	if resp.StatusCode/100 != 2 {
		t.Fatalf("disable bootstrap: status %d body=%s", resp.StatusCode, string(raw))
	}

	// Bootstrap admin should now be unauthorised on every endpoint.
	raw, resp, err = bootstrap.Do(ctx, http.MethodGet, "/api/v1/admin/admin-accounts", nil)
	if err != nil {
		t.Fatalf("bootstrap after disable: %v", err)
	}
	if resp.StatusCode != http.StatusUnauthorized {
		t.Fatalf("bootstrap should be unauthorized after disable: status %d body=%s", resp.StatusCode, string(raw))
	}
	_ = json.RawMessage(raw)
}
