// Connection-machinery tests, restricted to the pure parts (backoff, fatal
// close codes, READY/session bookkeeping, sequence tracking). Deliberately no
// live-gateway test — that path is exercised in staging, not CI.

package gateway

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

	"github.com/coder/websocket"
)

func TestBackoffDoublesAndCaps(t *testing.T) {
	want := []time.Duration{
		2 * time.Second, 4 * time.Second, 8 * time.Second, 16 * time.Second,
		32 * time.Second, 60 * time.Second, 60 * time.Second, 60 * time.Second,
	}
	d := backoffStart
	for i, w := range want {
		d = nextBackoff(d)
		if d != w {
			t.Fatalf("step %d: want %s, got %s", i, w, d)
		}
	}
}

func TestFatalCloseCodes(t *testing.T) {
	for _, c := range []websocket.StatusCode{4004, 4010, 4011, 4012, 4013, 4014} {
		if !isFatalClose(c) {
			t.Errorf("close code %d must be fatal (reconnecting loops forever)", c)
		}
	}
	// 4008 (rate limited) and 4009 (session timed out) are resumable; 4000 is
	// our own zombie close; -1 is CloseStatus's not-a-close-error sentinel.
	for _, c := range []websocket.StatusCode{-1, 1000, 1001, 4000, 4001, 4008, 4009} {
		if isFatalClose(c) {
			t.Errorf("close code %d must not be fatal", c)
		}
	}
}

func TestReadyCapturesResumeState(t *testing.T) {
	b := New("tok", &fakeGrader{})
	sess := &session{}
	d := []byte(`{"session_id":"abc","resume_gateway_url":"wss://resume.example/","user":{"id":"999"}}`)

	b.dispatch(context.Background(), payload{Op: opDispatch, T: "READY", D: d}, sess)

	if sess.sessionID != "abc" {
		t.Fatalf("want session id abc, got %q", sess.sessionID)
	}
	// Trailing slash trimmed, gateway query string appended — RESUME must go
	// to the session's own URL with the same v10/json parameters.
	if sess.resumeURL != "wss://resume.example/?v=10&encoding=json" {
		t.Fatalf("bad resume url: %q", sess.resumeURL)
	}
	if sess.userID != botID {
		t.Fatalf("want user id %s, got %q", botID, sess.userID)
	}
}

func TestReadyWithoutResumeURLLeavesItEmpty(t *testing.T) {
	b := New("tok", &fakeGrader{})
	sess := &session{resumeURL: "wss://stale.example/?v=10&encoding=json"}
	d := []byte(`{"session_id":"abc","user":{"id":"999"}}`)

	b.dispatch(context.Background(), payload{Op: opDispatch, T: "READY", D: d}, sess)

	if sess.resumeURL != "" {
		t.Fatalf("a READY without resume_gateway_url must clear the stale url, got %q", sess.resumeURL)
	}
}

func TestMessageCreateBeforeReadyIsIgnored(t *testing.T) {
	// Until READY supplies our user id we cannot detect mentions (or guard
	// against answering ourselves), so nothing may be handled.
	g := &fakeGrader{resp: json.RawMessage(`{}`)}
	b := New("tok", g)
	sess := &session{} // no userID yet
	d, err := json.Marshal(testMsg("<@999> Phoenix", mentioning(botID)))
	if err != nil {
		t.Fatalf("marshal: %v", err)
	}

	b.dispatch(context.Background(), payload{Op: opDispatch, T: "MESSAGE_CREATE", D: d}, sess)

	time.Sleep(20 * time.Millisecond)
	if g.callCount() != 0 {
		t.Fatal("pre-READY message must be ignored")
	}
}

func TestPayloadSequenceIsNullable(t *testing.T) {
	var withSeq, withoutSeq payload
	if err := json.Unmarshal([]byte(`{"op":0,"t":"X","s":7,"d":{}}`), &withSeq); err != nil {
		t.Fatalf("unmarshal: %v", err)
	}
	if withSeq.S == nil || *withSeq.S != 7 {
		t.Fatalf("want seq 7, got %v", withSeq.S)
	}
	if err := json.Unmarshal([]byte(`{"op":11,"s":null,"d":null}`), &withoutSeq); err != nil {
		t.Fatalf("unmarshal: %v", err)
	}
	if withoutSeq.S != nil {
		t.Fatalf("null seq must stay nil, got %v", *withoutSeq.S)
	}
}

func TestSessionSeqTracking(t *testing.T) {
	sess := &session{}
	if _, ok := sess.lastSeq(); ok {
		t.Fatal("fresh session must have no sequence number")
	}
	sess.setSeq(41)
	sess.setSeq(42)
	if seq, ok := sess.lastSeq(); !ok || seq != 42 {
		t.Fatalf("want seq 42, got %d (ok=%v)", seq, ok)
	}
}

// A malformed HELLO must be an ERROR, not a clean "reidentify". Run treats a
// clean return as a PLANNED reconnect: backoff resets to 1s and it redials with
// no sleep at all. So if these ever regress to returning nil, a gateway stuck
// sending a bad HELLO becomes a tight reconnect loop against Discord.
func TestParseHelloRejectsMalformedSoBackoffApplies(t *testing.T) {
	for _, tc := range []struct {
		name string
		raw  string
	}{
		{"not json", `{`},
		{"wrong op", `{"op":0,"d":{"heartbeat_interval":41250}}`},
		{"missing interval", `{"op":10,"d":{}}`},
		{"zero interval", `{"op":10,"d":{"heartbeat_interval":0}}`},
		{"negative interval", `{"op":10,"d":{"heartbeat_interval":-1}}`},
		{"interval wrong type", `{"op":10,"d":{"heartbeat_interval":"soon"}}`},
	} {
		t.Run(tc.name, func(t *testing.T) {
			got, err := parseHello([]byte(tc.raw))
			if err == nil {
				t.Fatalf("parseHello(%s) = %v, nil; want an error so Run applies backoff", tc.raw, got)
			}
			if got != 0 {
				t.Fatalf("parseHello(%s) interval = %v; want 0 on error", tc.raw, got)
			}
		})
	}
}

func TestParseHelloAcceptsValid(t *testing.T) {
	got, err := parseHello([]byte(`{"op":10,"d":{"heartbeat_interval":41250}}`))
	if err != nil {
		t.Fatalf("parseHello: unexpected error %v", err)
	}
	if want := 41250 * time.Millisecond; got != want {
		t.Fatalf("interval = %v; want %v", got, want)
	}
}

// Discord's advertised retry_after is clamped to 5s, matching the Python REST
// helper's _MAX_BACKOFF_S. Replies run on a small fixed worker pool, so a bogus
// server value must not park a slot for minutes.
func TestRetryAfterClamp(t *testing.T) {
	for _, tc := range []struct {
		name string
		body string
		want time.Duration
	}{
		{"honours a sane value", `{"retry_after":2}`, 2 * time.Second},
		{"clamps a hostile value", `{"retry_after":600}`, 5 * time.Second},
		{"defaults when absent", `{}`, 1 * time.Second},
	} {
		t.Run(tc.name, func(t *testing.T) {
			if got := retryAfter(http.Header{}, []byte(tc.body)); got != tc.want {
				t.Fatalf("retryAfter(%s) = %v; want %v", tc.body, got, tc.want)
			}
		})
	}
}
