package domaintest

import (
	"time"

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

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

func NewTribeSnapshotCursor(tb TestingTB, opts ...func(cfg *TribeSnapshotCursorConfig)) domain.TribeSnapshotCursor {
	tb.Helper()

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

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

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

	return psc
}

type TribeSnapshotConfig struct {
	ID          int
	TribeID     int
	ServerKey   string
	NumMembers  int
	NumVillages int
	Points      int
	AllPoints   int
	Rank        int
	OD          domain.OpponentsDefeated
	Dominance   float64
	Date        time.Time
	CreatedAt   time.Time
}

func NewTribeSnapshot(tb TestingTB, opts ...func(cfg *TribeSnapshotConfig)) domain.TribeSnapshot {
	tb.Helper()

	now := time.Now()

	cfg := &TribeSnapshotConfig{
		ID:          RandID(),
		TribeID:     RandID(),
		ServerKey:   RandServerKey(),
		NumMembers:  gofakeit.IntRange(1, 10000),
		NumVillages: gofakeit.IntRange(1, 10000),
		Points:      gofakeit.IntRange(1, 10000),
		AllPoints:   gofakeit.IntRange(1, 10000),
		Rank:        gofakeit.IntRange(1, 10000),
		OD:          NewOpponentsDefeated(tb),
		Dominance:   gofakeit.Float64Range(0.1, 100),
		Date:        now,
		CreatedAt:   now,
	}

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

	ts, err := domain.UnmarshalTribeSnapshotFromDatabase(
		cfg.ID,
		cfg.TribeID,
		cfg.ServerKey,
		cfg.NumMembers,
		cfg.NumVillages,
		cfg.Points,
		cfg.AllPoints,
		cfg.Rank,
		cfg.OD,
		cfg.Dominance,
		cfg.Date,
		cfg.CreatedAt,
	)
	require.NoError(tb, err)

	return ts
}

type TribeSnapshotWithRelationsConfig struct {
	TribeSnapshotOptions []func(cfg *TribeSnapshotConfig)
	TribeOptions         []func(cfg *TribeConfig)
}

func NewTribeSnapshotWithRelations(
	tb TestingTB,
	opts ...func(cfg *TribeSnapshotWithRelationsConfig),
) domain.TribeSnapshotWithRelations {
	tb.Helper()

	cfg := &TribeSnapshotWithRelationsConfig{}

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

	ts := NewTribeSnapshot(tb, cfg.TribeSnapshotOptions...)

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

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

	return ts.WithRelations(tribe)
}
