package domaintest

import (
	"time"

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

type VillageCursorConfig struct {
	ID        int
	ServerKey string
}

func NewVillageCursor(tb TestingTB, opts ...func(cfg *VillageCursorConfig)) domain.VillageCursor {
	tb.Helper()

	cfg := &VillageCursorConfig{
		ID:        RandID(),
		ServerKey: RandServerKey(),
	}

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

	pc, err := domain.NewVillageCursor(
		cfg.ID,
		cfg.ServerKey,
	)
	require.NoError(tb, err)

	return pc
}

type VillageConfig struct {
	ID        int
	ServerKey string
	PlayerID  int
}

func NewVillage(tb TestingTB, opts ...func(cfg *VillageConfig)) domain.Village {
	tb.Helper()

	cfg := &VillageConfig{
		ID:        RandID(),
		ServerKey: RandServerKey(),
		PlayerID:  gofakeit.IntRange(0, 10000),
	}

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

	v, err := domain.UnmarshalVillageFromDatabase(
		cfg.ID,
		cfg.ServerKey,
		gofakeit.LetterN(50),
		gofakeit.IntRange(1, 10000),
		gofakeit.IntRange(1, 999),
		gofakeit.IntRange(1, 999),
		gofakeit.LetterN(3),
		0,
		cfg.PlayerID,
		gofakeit.URL(),
		time.Now(),
	)
	require.NoError(tb, err)

	return v
}

type VillageWithRelationsConfig struct {
	PlayerOptions []func(cfg *PlayerWithRelationsConfig)
}

func NewVillageWithRelations(tb TestingTB, opts ...func(cfg *VillageWithRelationsConfig)) domain.VillageWithRelations {
	tb.Helper()

	cfg := &VillageWithRelationsConfig{}

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

	v := NewVillage(tb)

	var playerMeta domain.PlayerMetaWithRelations
	if v.PlayerID() > 0 {
		playerMeta = NewPlayerWithRelations(tb, cfg.PlayerOptions...).Meta()
	}

	return v.WithRelations(domain.NullPlayerMetaWithRelations{
		V:     playerMeta,
		Valid: !playerMeta.IsZero(),
	})
}
