package integration_test

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

	"galaxy/integration/testenv"
)

// TestEngineCommandProxy spins up a running game (10 enrolled
// pilots so engine init succeeds) and verifies that backend's
// user-side `/api/v1/user/games/{id}/commands` proxy reaches the
// engine and returns its passthrough body without an internal-error
// response.
func TestEngineCommandProxy(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+cmd@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":             "Engine Command Proxy",
		"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"`
	}
	_ = json.Unmarshal(raw, &game)

	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: %v %d", err, resp.StatusCode)
	}
	pilots := testenv.EnrollPilots(t, plat, ownerHTTP, game.GameID, 10, "cmd")

	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: %v %d", err, resp.StatusCode)
	}

	// Wait until runtime is running.
	deadline := time.Now().Add(3 * time.Minute)
	for time.Now().Before(deadline) {
		raw, resp, err = admin.Do(ctx, http.MethodGet, "/api/v1/admin/runtimes/"+game.GameID, nil)
		if err == nil && resp.StatusCode == http.StatusOK {
			var rec struct {
				Status string `json:"status"`
			}
			_ = json.Unmarshal(raw, &rec)
			if rec.Status == "running" {
				break
			}
		}
		time.Sleep(500 * time.Millisecond)
	}

	// Pilot 1 sends a command. Backend forwards to the engine; the
	// pass-through body comes back unchanged. We accept any status
	// the engine produces (200, 4xx) — what matters is that backend
	// did not surface an internal error of its own.
	cmdBody := map[string]any{"actions": []map[string]any{}}
	raw, resp, err = pilots[0].HTTP.Do(ctx, http.MethodPost, "/api/v1/user/games/"+game.GameID+"/commands", cmdBody)
	if err != nil {
		t.Fatalf("commands proxy: %v", err)
	}
	if resp.StatusCode == http.StatusInternalServerError || resp.StatusCode == http.StatusBadGateway {
		t.Fatalf("commands proxy: backend internal-error %d body=%s", resp.StatusCode, string(raw))
	}

	// Cleanup: stop the container so the test does not leak it.
	_, _, _ = admin.Do(ctx, http.MethodPost, "/api/v1/admin/games/"+game.GameID+"/force-stop", nil)
}
