package domaintest

import (
	"time"

	"gitea.dwysokinski.me/twhelp/corev3/internal/domain"
	"github.com/brianvoe/gofakeit/v7"
	"github.com/stretchr/testify/require"
)

type PlayerSnapshotCursorConfig struct {
	ID        int
	ServerKey string
	Date      time.Time
}

func NewPlayerSnapshotCursor(tb TestingTB, opts ...func(cfg *PlayerSnapshotCursorConfig)) domain.PlayerSnapshotCursor {
	tb.Helper()

	cfg := &PlayerSnapshotCursorConfig{
		ID:        RandID(),
		ServerKey: RandServerKey(),
		Date:      gofakeit.Date(),
	}

	for _, opt := range opts {
		opt(cfg)
	}

	psc, err := domain.NewPlayerSnapshotCursor(
		cfg.ID,
		cfg.ServerKey,
		cfg.Date,
	)
	require.NoError(tb, err)

	return psc
}

type PlayerSnapshotConfig struct {
	ID          int
	PlayerID    int
	ServerKey   string
	NumVillages int
	Points      int
	Rank        int
	TribeID     int
	OD          domain.OpponentsDefeated
	Date        time.Time
	CreatedAt   time.Time
}

func NewPlayerSnapshot(tb TestingTB, opts ...func(cfg *PlayerSnapshotConfig)) domain.PlayerSnapshot {
	tb.Helper()

	now := time.Now()

	cfg := &PlayerSnapshotConfig{
		ID:          RandID(),
		PlayerID:    RandID(),
		ServerKey:   RandServerKey(),
		NumVillages: gofakeit.IntRange(1, 10000),
		Points:      gofakeit.IntRange(1, 10000),
		Rank:        gofakeit.IntRange(1, 10000),
		TribeID:     RandID(),
		OD:          NewOpponentsDefeated(tb),
		Date:        now,
		CreatedAt:   now,
	}

	for _, opt := range opts {
		opt(cfg)
	}

	ps, err := domain.UnmarshalPlayerSnapshotFromDatabase(
		cfg.ID,
		cfg.PlayerID,
		cfg.ServerKey,
		cfg.NumVillages,
		cfg.Points,
		cfg.Rank,
		cfg.TribeID,
		cfg.OD,
		cfg.Date,
		cfg.CreatedAt,
	)
	require.NoError(tb, err)

	return ps
}

type PlayerSnapshotWithRelationsConfig struct {
	PlayerSnapshotOptions []func(cfg *PlayerSnapshotConfig)
	PlayerOptions         []func(cfg *PlayerConfig)
	TribeOptions          []func(cfg *TribeConfig)
}

func NewPlayerSnapshotWithRelations(
	tb TestingTB,
	opts ...func(cfg *PlayerSnapshotWithRelationsConfig),
) domain.PlayerSnapshotWithRelations {
	tb.Helper()

	cfg := &PlayerSnapshotWithRelationsConfig{}

	for _, opt := range opts {
		opt(cfg)
	}

	ps := NewPlayerSnapshot(tb, cfg.PlayerSnapshotOptions...)

	if ps.PlayerID() > 0 {
		cfg.PlayerOptions = append([]func(cfg *PlayerConfig){
			func(cfg *PlayerConfig) {
				cfg.ID = ps.ID()
			},
		}, cfg.PlayerOptions...)
	}

	if ps.TribeID() > 0 {
		cfg.TribeOptions = append([]func(cfg *TribeConfig){
			func(cfg *TribeConfig) {
				cfg.ID = ps.ID()
			},
		}, cfg.TribeOptions...)
	}

	var player domain.PlayerMeta
	if len(cfg.PlayerOptions) > 0 {
		player = NewPlayer(tb, cfg.PlayerOptions...).Meta()
	}

	var tribe domain.TribeMeta
	if len(cfg.TribeOptions) > 0 {
		tribe = NewTribe(tb, cfg.TribeOptions...).Meta()
	}

	return ps.WithRelations(player, domain.NullTribeMeta{
		V:     tribe,
		Valid: tribe.IsZero(),
	})
}
