package app

import (
	"context"

	"gitea.dwysokinski.me/twhelp/corev3/internal/domain"
)

type TribeChangeRepository interface {
	// Create persists tribe changes in a store (e.g. Postgres).
	// If there is a similar tribe change, such changes are ignored.
	// Similar means that there is a tribe change with the same player id,
	// new tribe id and old tribe id and this tribe change was created within the same hour.
	Create(ctx context.Context, params ...domain.CreateTribeChangeParams) error
}

type TribeChangeService struct {
	repo TribeChangeRepository
}

func NewTribeChangeService(repo TribeChangeRepository) *TribeChangeService {
	return &TribeChangeService{repo: repo}
}

const (
	tribeChangeChunkSize = 500
)

func (svc *TribeChangeService) Create(ctx context.Context, params ...domain.CreateTribeChangeParams) error {
	for i := 0; i < len(params); i += tribeChangeChunkSize {
		end := i + tribeChangeChunkSize
		if end > len(params) {
			end = len(params)
		}

		if err := svc.repo.Create(ctx, params[i:end]...); err != nil {
			return err
		}
	}

	return nil
}
