tercul-backend/services/localization_service.go
Damir Mukimov fa336cacf3
wip
2025-09-01 00:43:59 +02:00

85 lines
2.3 KiB
Go

package services
import (
"context"
"errors"
"tercul/internal/models"
"tercul/internal/repositories"
)
// LocalizationService resolves localized attributes using translations
type LocalizationService interface {
GetWorkContent(ctx context.Context, workID uint, preferredLanguage string) (string, error)
GetAuthorBiography(ctx context.Context, authorID uint, preferredLanguage string) (string, error)
}
type localizationService struct {
translationRepo repositories.TranslationRepository
}
func NewLocalizationService(translationRepo repositories.TranslationRepository) LocalizationService {
return &localizationService{translationRepo: translationRepo}
}
func (s *localizationService) GetWorkContent(ctx context.Context, workID uint, preferredLanguage string) (string, error) {
if workID == 0 {
return "", errors.New("invalid work ID")
}
translations, err := s.translationRepo.ListByWorkID(ctx, workID)
if err != nil {
return "", err
}
return pickContent(translations, preferredLanguage), nil
}
func (s *localizationService) GetAuthorBiography(ctx context.Context, authorID uint, preferredLanguage string) (string, error) {
if authorID == 0 {
return "", errors.New("invalid author ID")
}
translations, err := s.translationRepo.ListByEntity(ctx, "Author", authorID)
if err != nil {
return "", err
}
// Prefer Description from Translation as biography proxy
var byLang *models.Translation
for i := range translations {
tr := &translations[i]
if tr.IsOriginalLanguage && tr.Description != "" {
return tr.Description, nil
}
if tr.Language == preferredLanguage && byLang == nil && tr.Description != "" {
byLang = tr
}
}
if byLang != nil {
return byLang.Description, nil
}
// fallback to any non-empty description
for i := range translations {
if translations[i].Description != "" {
return translations[i].Description, nil
}
}
return "", nil
}
func pickContent(translations []models.Translation, preferredLanguage string) string {
var byLang *models.Translation
for i := range translations {
tr := &translations[i]
if tr.IsOriginalLanguage {
return tr.Content
}
if tr.Language == preferredLanguage && byLang == nil {
byLang = tr
}
}
if byLang != nil {
return byLang.Content
}
if len(translations) > 0 {
return translations[0].Content
}
return ""
}