package server

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"testing"

	"tinyadventure/internal/model"
)

const testPlayer = "0123456789abcdef0123456789abcdef"

type client struct {
	t      *testing.T
	ts     *httptest.Server
	player string
}

func open(t *testing.T, seed model.Seed, dir string) (*Server, client) {
	srv, err := New(seed, t.TempDir(), dir)
	if err != nil {
		t.Fatal(err)
	}
	ts := httptest.NewServer(srv)
	t.Cleanup(ts.Close)
	return srv, client{t, ts, testPlayer}
}

func (c client) raw(method, path string, body any) (*http.Response, []byte) {
	c.t.Helper()
	b, _ := json.Marshal(body)
	req, _ := http.NewRequest(method, c.ts.URL+path, bytes.NewReader(b))
	req.Header.Set("X-Player", c.player)
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		c.t.Fatal(err)
	}
	defer res.Body.Close()
	out, _ := io.ReadAll(res.Body)
	return res, out
}

func (c client) call(method, path string, body any, want int) model.GameState {
	c.t.Helper()
	res, b := c.raw(method, path, body)
	if res.StatusCode != want {
		c.t.Fatalf("%s %s: status %d, want %d: %s", method, path, res.StatusCode, want, b)
	}
	var st model.GameState
	json.Unmarshal(b, &st)
	return st
}

func firstFight(t *testing.T, c client) model.GameState {
	st := c.call("GET", "/api/state", nil, 200)
	p := (&game{state: st}).poi(st.Campaign.Main.Steps[0].POI)
	c.call("POST", "/api/move", model.Action{X: p.X, Y: p.Y}, 200)
	return c.call("POST", "/api/interact", model.Action{ID: p.ID}, 200)
}

func TestHTTPFlow(t *testing.T) {
	_, c := open(t, 7, "")
	st := c.call("GET", "/api/state", nil, 200)
	if st.Phase != "explore" || st.Shop == nil || st.Clock.Day != 1 || st.Feedback {
		t.Fatalf("bad start: %s shop %v clock %+v feedback %v", st.Phase, st.Shop, st.Clock, st.Feedback)
	}
	if st = c.call("POST", "/api/buy", model.Action{Item: "supplies"}, 200); st.Party.Supplies != startSupplies+1 {
		t.Fatalf("supplies %d", st.Party.Supplies)
	}
	st = firstFight(t, c)
	if len(st.Log) == 0 || st.Encounter == nil || st.Summary.Battles != 1 || st.Summary.Dealt == 0 {
		t.Fatalf("fight without log, encounter or tally: %+v", st.Summary)
	}
	c.call("POST", "/api/sell", model.Action{Item: "nope"}, 400)
	c.call("POST", "/api/nope", nil, 404)
}

func TestRejections(t *testing.T) {
	_, c := open(t, 3, "")
	c.call("POST", "/api/move", model.Action{X: -1, Y: 0}, 400)
	c.call("POST", "/api/interact", model.Action{ID: "nope"}, 400)
	c.call("POST", "/api/equip", model.Action{Unit: "u1", Item: "nope"}, 400)
	res, _ := c.raw("POST", "/api/feedback", model.Action{Text: strings.Repeat("a", maxBody)})
	if res.StatusCode != 400 {
		t.Fatalf("oversized body gave %d", res.StatusCode)
	}
}

func TestPlayersGetTheirOwnBoards(t *testing.T) {
	_, a := open(t, 11, "")
	b := a
	b.player = strings.Repeat("f", 32)
	sp := a.call("GET", "/api/state", nil, 200).Map.Spawns[1]
	a.call("POST", "/api/move", model.Action{X: sp.X, Y: sp.Y}, 200)
	if st := b.call("GET", "/api/state", nil, 200); st.Clock.Time != 0 || st.Game == a.call("GET", "/api/state", nil, 200).Game {
		t.Fatalf("second player shares the first board: %+v", st.Clock)
	}
	res, _ := http.Get(a.ts.URL + "/api/state")
	if c := res.Cookies(); len(c) != 1 || c[0].Name != cookieName || !c[0].HttpOnly || !playerID.MatchString(c[0].Value) {
		t.Fatalf("cookie %+v", c)
	}
}

func TestNewCampaign(t *testing.T) {
	_, c := open(t, 11, "")
	a := c.call("GET", "/api/state", nil, 200)
	sp := a.Map.Spawns[1]
	c.call("POST", "/api/move", model.Action{X: sp.X, Y: sp.Y}, 200)
	b := c.call("POST", "/api/new", nil, 200)
	if b.Seed == a.Seed || b.Game == a.Game || b.Clock.Time != 0 || b.Phase != "explore" {
		t.Fatalf("not fresh: %d vs %d %+v", a.Seed, b.Seed, b.Clock)
	}
	if d := c.call("POST", "/api/new", map[string]int{"seed": 99}, 200); d.Seed != 99 {
		t.Fatalf("seed %d", d.Seed)
	}
}

func TestFinishedCampaignRejectsActions(t *testing.T) {
	srv, c := open(t, 7, "")
	g, _ := srv.game(testPlayer)
	g.state.Phase = "defeat"
	c.call("POST", "/api/move", model.Action{X: 1, Y: 1}, 400)
	if st := c.call("GET", "/api/state", nil, 200); st.Phase != "defeat" {
		t.Fatalf("phase %s", st.Phase)
	}
	c.call("POST", "/api/new", nil, 200)
}

func TestPathPreviewMatchesTheWalk(t *testing.T) {
	srv, c := open(t, 7, "")
	g, _ := srv.game(testPlayer)
	tx, ty := g.state.Party.X+3, g.state.Party.Y
	for !g.state.Map.Walkable(tx, ty) || g.blocker(tx, ty) != "" {
		tx++
	}
	res, b := c.raw("GET", "/api/path?x="+strconv.Itoa(tx)+"&y="+strconv.Itoa(ty), nil)
	var route model.Route
	json.Unmarshal(b, &route)
	want, _ := g.path(tx, ty)
	if res.StatusCode != 200 || len(route.Path) == 0 || route.Time <= 0 || route.Path[len(route.Path)-1] != want[len(route.Path)-1] {
		t.Fatalf("route %+v want %v", route, want)
	}
	if res, _ := c.raw("GET", "/api/path?x=a&y=1", nil); res.StatusCode != 400 {
		t.Fatalf("bad query gave %d", res.StatusCode)
	}
}

func TestPathPreviewCountsTheHazardHp(t *testing.T) {
	for seed := model.Seed(1); seed <= 20; seed++ {
		srv, c := open(t, seed, "")
		g, _ := srv.game(testPlayer)
		hp := func() int {
			n := 0
			for _, u := range g.state.Party.Units {
				n += u.Stats.HP
			}
			return n
		}
		for dx := -6; dx <= 6; dx++ {
			for dy := -6; dy <= 6; dy++ {
				tx, ty := g.state.Party.X+dx, g.state.Party.Y+dy
				route, err := g.route(tx, ty)
				if err != nil || route.Hazard == 0 || route.Blocked != "" {
					continue
				}
				before := hp()
				c.call("POST", "/api/move", model.Action{X: tx, Y: ty}, 200)
				if g.state.Party.X != tx || g.state.Party.Y != ty {
					t.Skipf("seed %d: a band cut the walk short", seed)
				}
				if lost := before - hp(); lost != route.Hazard {
					t.Fatalf("seed %d: preview %d hp, walk cost %d", seed, route.Hazard, lost)
				}
				return
			}
		}
	}
	t.Fatal("no route with a hazard near any spawn")
}

func TestTheLogReplaysToTheSameGame(t *testing.T) {
	dir := t.TempDir()
	srv, c := open(t, 7, dir)
	c.call("POST", "/api/buy", model.Action{Item: "supplies"}, 200)
	c.call("POST", "/api/sell", model.Action{Item: "nothing"}, 400)
	live := firstFight(t, c)
	for _, it := range live.Party.Inventory {
		c.call("POST", "/api/equip", model.Action{Unit: live.Party.Units[0].ID, Item: it.ID}, 200)
	}
	live = c.call("GET", "/api/state", nil, 200)
	srv.seats = map[string]*seat{}
	again := c.call("GET", "/api/state", nil, 200)
	again.Summary.Seconds, live.Summary.Seconds = 0, 0
	a, _ := json.Marshal(live)
	b, _ := json.Marshal(again)
	if !bytes.Equal(a, b) {
		t.Fatalf("replay differs from the live game")
	}
	log, _ := os.ReadFile(filepath.Join(dir, "games", live.Game+".jsonl"))
	if n := bytes.Count(log, []byte("\n")); n < 4 || bytes.Contains(log, []byte(testPlayer)) || !bytes.Contains(log, []byte(`"err"`)) {
		t.Fatalf("log has %d lines or names the player:\n%s", n, log)
	}
}

func TestBoardsThatNoLongerReplayStartOver(t *testing.T) {
	for name, edit := range map[string]func([]byte) []byte{
		"older rules": func(b []byte) []byte {
			return bytes.Replace(b, []byte(fmt.Sprintf(`"version":%d`, model.Version)), []byte(`"version":0`), 1)
		},
		"a rejected step": func(b []byte) []byte {
			return append(b, []byte(`{"kind":"equip","t":1,"unit":"u1","item":"gone"}`+"\n")...)
		},
	} {
		dir := t.TempDir()
		srv, c := open(t, 7, dir)
		old := firstFight(t, c)
		file := filepath.Join(dir, "games", old.Game+".jsonl")
		b, _ := os.ReadFile(file)
		os.WriteFile(file, edit(b), 0o644)
		srv.seats = map[string]*seat{}
		st := c.call("GET", "/api/state", nil, 200)
		if st.Game == old.Game || st.Summary.Battles != 0 {
			t.Fatalf("%s: got game %s with %d battles", name, st.Game, st.Summary.Battles)
		}
		after, _ := os.ReadFile(file)
		if !bytes.Equal(after, edit(b)) {
			t.Fatalf("%s: the old log changed", name)
		}
	}
}

func TestFeedbackOpensAfterAFightAndAGearChange(t *testing.T) {
	dir := t.TempDir()
	srv, c := open(t, 7, dir)
	c.call("POST", "/api/feedback", model.Action{Text: "hello there"}, 400)
	st := firstFight(t, c)
	g, _ := srv.game(testPlayer)
	if st.Feedback || len(st.Party.Inventory) == 0 {
		g.state.Party.Inventory = append(g.state.Party.Inventory, model.Item{ID: "t1", Name: "Test Ring", Slot: model.SlotTrinket, Rarity: "common"})
	}
	id := g.state.Party.Inventory[0].ID
	if st = c.call("POST", "/api/equip", model.Action{Unit: st.Party.Units[0].ID, Item: id}, 200); !st.Feedback {
		t.Fatal("feedback stays closed after a fight and a gear change")
	}
	c.call("POST", "/api/feedback", model.Action{Text: " "}, 400)
	c.call("POST", "/api/feedback", model.Action{Text: "The boss was hard"}, 200)
	b, _ := os.ReadFile(filepath.Join(dir, "feedback.jsonl"))
	if !bytes.Contains(b, []byte("The boss was hard")) || !bytes.Contains(b, []byte(st.Game)) {
		t.Fatalf("feedback file: %s", b)
	}
}

func TestFinishedRunsAreShareable(t *testing.T) {
	dir := t.TempDir()
	srv, c := open(t, 7, dir)
	os.WriteFile(filepath.Join(srv.web, "index.html"), []byte("<head>\n<title>Tiny Adventure</title><meta name=\"description\" content=\"x\">\n</head>"), 0o644)
	st := firstFight(t, c)
	if res, _ := c.raw("GET", "/api/run/"+st.Game, nil); res.StatusCode != 404 {
		t.Fatalf("unfinished run gave %d", res.StatusCode)
	}
	g, _ := srv.game(testPlayer)
	g.state.Phase = "victory"
	res, b := c.raw("GET", "/api/run/"+st.Game, nil)
	var run model.Run
	json.Unmarshal(b, &run)
	if res.StatusCode != 200 || run.Seed != 7 || len(run.Party) != 4 || run.Boss == "" || run.KeysOf == 0 {
		t.Fatalf("run %d %+v", res.StatusCode, run)
	}
	if _, page := c.raw("GET", "/r/"+st.Game, nil); !bytes.Contains(page, []byte(`og:image" content="http://`)) || !bytes.Contains(page, []byte("Victory on day")) || bytes.Contains(page, []byte(`content="x"`)) {
		t.Fatalf("share page: %s", page)
	}
	res, png := c.raw("GET", "/r/"+st.Game+"/card.png", nil)
	if res.StatusCode != 200 || !bytes.HasPrefix(png, []byte("\x89PNG")) {
		t.Fatalf("card %d, %d bytes", res.StatusCode, len(png))
	}
	if res, _ := c.raw("GET", "/api/run/../../etc", nil); res.StatusCode == 200 {
		t.Fatal("path traversal answered")
	}
}

func TestProxiedClientsAreRateLimited(t *testing.T) {
	_, c := open(t, 7, "")
	status := 0
	for range 30 {
		req, _ := http.NewRequest("POST", c.ts.URL+"/api/new", nil)
		req.Header.Set("X-Forwarded-For", "203.0.113.9")
		res, err := http.DefaultClient.Do(req)
		if err != nil {
			t.Fatal(err)
		}
		res.Body.Close()
		status = res.StatusCode
	}
	if status != http.StatusTooManyRequests {
		t.Fatalf("thirty new games in a row gave %d", status)
	}
	c.call("POST", "/api/new", nil, 200)
}
