package app

import (
	"context"

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

type TribeChangeRepository interface {
	// Create persists tribe changes in a store (e.g. Postgres).
	// Duplicates are ignored.
	Create(ctx context.Context, params ...domain.CreateTribeChangeParams) error
	List(ctx context.Context, params domain.ListTribeChangesParams) (domain.ListTribeChangesResult, error)
	ListWithRelations(
		ctx context.Context,
		params domain.ListTribeChangesParams,
	) (domain.ListTribeChangesWithRelationsResult, 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
}

func (svc *TribeChangeService) List(
	ctx context.Context,
	params domain.ListTribeChangesParams,
) (domain.ListTribeChangesResult, error) {
	return svc.repo.List(ctx, params)
}

func (svc *TribeChangeService) ListWithRelations(
	ctx context.Context,
	params domain.ListTribeChangesParams,
) (domain.ListTribeChangesWithRelationsResult, error) {
	return svc.repo.ListWithRelations(ctx, params)
}
