package integration_test

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

	"galaxy/integration/testenv"
)

// TestRuntimeLifecycle drives the runtime control plane against a
// real `galaxy/game:integration` container with the engine's
// production race-count requirement (`len(races) >= 10`) honoured.
// The owner creates an enrollment-open game, ten pilots redeem
// per-game invites, admin force-starts, and the test waits for the
// runtime record to reach `running`. It then triggers force-stop and
// asserts the runtime exits the active set.
func TestRuntimeLifecycle(t *testing.T) {
	plat := testenv.Bootstrap(t, testenv.BootstrapOptions{})
	testenv.EnsureGameImage(t)
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
	defer cancel()

	admin := testenv.NewBackendAdminClient(plat.Backend.HTTPURL, plat.Backend.AdminUser, plat.Backend.AdminPassword)
	if _, resp, err := admin.Do(ctx, http.MethodPost, "/api/v1/admin/engine-versions", map[string]any{
		"version": "v1.0.0", "image_ref": testenv.GameImage, "enabled": true,
	}); err != nil || resp.StatusCode/100 != 2 {
		t.Fatalf("seed engine_version: err=%v resp=%v", err, resp)
	}

	owner := testenv.RegisterSession(t, plat, "owner+runtime@example.com")
	ownerID, err := owner.LookupUserID(ctx, plat)
	if err != nil {
		t.Fatalf("resolve owner: %v", err)
	}
	ownerHTTP := testenv.NewBackendUserClient(plat.Backend.HTTPURL, ownerID)

	gameBody := map[string]any{
		"game_name":             "Runtime Lifecycle",
		"visibility":            "private",
		"min_players":           10,
		"max_players":           10,
		"start_gap_hours":       1,
		"start_gap_players":     10,
		"enrollment_ends_at":    time.Now().Add(24 * time.Hour).UTC().Format(time.RFC3339),
		"turn_schedule":         "0 * * * *",
		"target_engine_version": "v1.0.0",
	}
	raw, resp, err := ownerHTTP.Do(ctx, http.MethodPost, "/api/v1/user/lobby/games", gameBody)
	if err != nil || resp.StatusCode != http.StatusCreated {
		t.Fatalf("create game: err=%v status=%d body=%s", err, resp.StatusCode, string(raw))
	}
	var game struct {
		GameID string `json:"game_id"`
	}
	if err := json.Unmarshal(raw, &game); err != nil {
		t.Fatalf("decode game: %v", err)
	}
	if _, resp, err := ownerHTTP.Do(ctx, http.MethodPost, "/api/v1/user/lobby/games/"+game.GameID+"/open-enrollment", nil); err != nil || resp.StatusCode != http.StatusOK {
		t.Fatalf("open enrollment: err=%v status=%d", err, resp.StatusCode)
	}

	// Engine init requires len(races) >= 10; enroll exactly that.
	testenv.EnrollPilots(t, plat, ownerHTTP, game.GameID, 10, "runtime")

	if _, resp, err := admin.Do(ctx, http.MethodPost, "/api/v1/admin/games/"+game.GameID+"/force-start", nil); err != nil || resp.StatusCode/100 != 2 {
		t.Fatalf("force-start: err=%v status=%d", err, resp.StatusCode)
	}

	// Wait for runtime to reach `running` against the live engine.
	deadline := time.Now().Add(3 * time.Minute)
	var runtimeStatus string
	for time.Now().Before(deadline) {
		raw, resp, err = admin.Do(ctx, http.MethodGet, "/api/v1/admin/runtimes/"+game.GameID, nil)
		if err != nil {
			t.Fatalf("admin runtime get: %v", err)
		}
		if resp.StatusCode == http.StatusOK {
			var rec struct {
				Status             string `json:"status"`
				CurrentContainerID string `json:"current_container_id"`
			}
			if err := json.Unmarshal(raw, &rec); err == nil {
				runtimeStatus = rec.Status
				if rec.Status == "running" {
					if rec.CurrentContainerID == "" {
						t.Fatalf("runtime running but current_container_id is empty")
					}
					break
				}
			}
		}
		time.Sleep(500 * time.Millisecond)
	}
	if runtimeStatus != "running" {
		t.Fatalf("runtime did not reach running within 3 m (last=%q body=%s)", runtimeStatus, string(raw))
	}

	// Force-stop and assert the runtime row exits the active set.
	if _, resp, err := admin.Do(ctx, http.MethodPost, "/api/v1/admin/games/"+game.GameID+"/force-stop", nil); err != nil || resp.StatusCode/100 != 2 {
		t.Fatalf("force-stop: err=%v status=%d", err, resp.StatusCode)
	}
	deadline = time.Now().Add(60 * time.Second)
	for time.Now().Before(deadline) {
		raw, resp, err = admin.Do(ctx, http.MethodGet, "/api/v1/admin/runtimes/"+game.GameID, nil)
		if err != nil {
			t.Fatalf("admin runtime get post-stop: %v", err)
		}
		if resp.StatusCode == http.StatusNotFound {
			return
		}
		var rec struct {
			Status string `json:"status"`
		}
		if err := json.Unmarshal(raw, &rec); err == nil {
			if rec.Status == "removed" || rec.Status == "stopped" || rec.Status == "cancelled" {
				return
			}
		}
		time.Sleep(500 * time.Millisecond)
	}
	t.Fatalf("runtime did not exit running within 60 s (last body=%s)", string(raw))
}
