package controller_test

import (
	"fmt"
	"path/filepath"
	"strings"
	"testing"

	"galaxy/util"

	"galaxy/game/internal/controller"
	"galaxy/game/internal/model/game"
	"galaxy/game/internal/repo"

	"github.com/google/uuid"
	"github.com/stretchr/testify/assert"
)

func TestNewGame(t *testing.T) {
	root, cleanup := util.CreateWorkDir(t)
	defer cleanup()

	r, err := repo.NewFileRepo(root)
	assert.NoError(t, err)

	players := 20
	races := make([]string, players)
	for i := range players {
		races[i] = fmt.Sprintf("race_%02d", i)
	}
	assert.NoError(t, r.Lock())
	gameID, err := controller.NewGame(r, races)
	assert.NoError(t, err)

	assert.FileExists(t, filepath.Join(root, "state.json"))
	assert.FileExists(t, filepath.Join(root, "0000/state.json"))

	g, err := r.LoadState()
	assert.NoError(t, err)
	assert.Equal(t, gameID, g.ID)
	assert.Equal(t, uint(0), g.Turn)
	assert.Equal(t, players, len(g.Race))

	for r := range g.Race {
		assert.NotEqual(t, uuid.Nil, g.Race[r].ID)
		assert.Equal(t, players-1, len(g.Race[r].Relations))
		assert.Equal(t, uint(10), g.Race[r].TTL)
		for i := range g.Race[r].Relations {
			assert.NotEqual(t, uuid.Nil, g.Race[r].Relations[i].RaceID)
			if g.Race[r].Relations[i].RaceID == g.Race[r].ID {
				assert.Fail(t, "race relation with itself")
			}
			assert.Equal(t, game.RelationWar, g.Race[r].Relations[i].Relation)
		}
	}

	numShuffled := false
	for i := range g.Map.Planet {
		p := &g.Map.Planet[i]
		if strings.HasPrefix(p.Name, "HW") || strings.HasPrefix(p.Name, "DW") {
			assert.True(t, p.Owned())
			assert.NotNil(t, p.Owner)
			assert.NotEqual(t, uuid.Nil, *p.Owner)
		}
		numShuffled = numShuffled || p.Number != uint(i)
	}
	assert.True(t, numShuffled)

	assert.NoError(t, r.Release())
}
