package integration_test

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

	"galaxy/integration/testenv"
)

// TestAdminEngineVersionsCRUD covers the engine-version registry: a
// single admin creates, updates, disables a version. A user attempting
// the same endpoint with X-User-ID is rejected (Basic Auth required).
func TestAdminEngineVersionsCRUD(t *testing.T) {
	plat := testenv.Bootstrap(t, testenv.BootstrapOptions{})
	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
	defer cancel()

	admin := testenv.NewBackendAdminClient(plat.Backend.HTTPURL, plat.Backend.AdminUser, plat.Backend.AdminPassword)
	raw, resp, err := admin.Do(ctx, http.MethodPost, "/api/v1/admin/engine-versions", map[string]any{
		"version":  "v1.0.0",
		"image_ref": "galaxy/game:integration",
		"enabled":  true,
	})
	if err != nil || resp.StatusCode/100 != 2 {
		t.Fatalf("create version: err=%v status=%d body=%s", err, resp.StatusCode, string(raw))
	}

	// Update image_ref + enabled flag.
	raw, resp, err = admin.Do(ctx, http.MethodPatch, "/api/v1/admin/engine-versions/v1.0.0", map[string]any{
		"image_ref": "galaxy/game:integration",
		"enabled":  false,
	})
	if err != nil || resp.StatusCode != http.StatusOK {
		t.Fatalf("update version: err=%v status=%d body=%s", err, resp.StatusCode, string(raw))
	}

	// Disable explicitly through the dedicated endpoint.
	raw, resp, err = admin.Do(ctx, http.MethodPost, "/api/v1/admin/engine-versions/v1.0.0/disable", nil)
	if err != nil || resp.StatusCode != http.StatusOK {
		t.Fatalf("disable version: err=%v status=%d body=%s", err, resp.StatusCode, string(raw))
	}

	// A regular user surface must not have access to this admin endpoint.
	noAuth := testenv.NewBackendAdminClient(plat.Backend.HTTPURL, "wrong", "wrong")
	raw, resp, err = noAuth.Do(ctx, http.MethodGet, "/api/v1/admin/engine-versions", nil)
	if err != nil {
		t.Fatalf("unauth call: %v", err)
	}
	if resp.StatusCode != http.StatusUnauthorized {
		t.Fatalf("unauth status = %d body=%s, want 401", resp.StatusCode, string(raw))
	}
}
