package app

import (
	"context"

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

type VersionRepository interface {
	List(ctx context.Context, params domain.ListVersionsParams) (domain.ListVersionsResult, error)
}

type VersionService struct {
	repo VersionRepository
}

func NewVersionService(repo VersionRepository) *VersionService {
	return &VersionService{repo: repo}
}

func (svc *VersionService) List(
	ctx context.Context,
	params domain.ListVersionsParams,
) (domain.ListVersionsResult, error) {
	return svc.repo.List(ctx, params)
}

func (svc *VersionService) Get(ctx context.Context, code string) (domain.Version, error) {
	params := domain.NewListVersionsParams()
	if err := params.SetCodes([]string{code}); err != nil {
		return domain.Version{}, err
	}

	res, err := svc.repo.List(ctx, params)
	if err != nil {
		return domain.Version{}, err
	}

	versions := res.Versions()
	if len(versions) == 0 {
		return domain.Version{}, domain.VersionNotFoundError{
			VersionCode: code,
		}
	}

	return versions[0], nil
}
