package enrichment

import (
	"context"
	"fmt"
	"tercul/internal/domain"
	"tercul/internal/platform/openlibrary"
)

// OpenLibraryAuthorEnricher enriches author data from the Open Library API.
type OpenLibraryAuthorEnricher struct {
	client *openlibrary.Client
}

// NewOpenLibraryAuthorEnricher creates a new OpenLibraryAuthorEnricher.
func NewOpenLibraryAuthorEnricher() *OpenLibraryAuthorEnricher {
	return &OpenLibraryAuthorEnricher{
		client: openlibrary.NewClient(),
	}
}

// Name returns the name of the enricher.
func (e *OpenLibraryAuthorEnricher) Name() string {
	return "openlibrary_author_enricher"
}

// Enrich fetches data from the Open Library API and enriches the author.
func (e *OpenLibraryAuthorEnricher) Enrich(ctx context.Context, author *domain.Author) error {
	if author.OpenLibraryID == "" {
		// No OLID to look up.
		return nil
	}

	olAuthor, err := e.client.GetAuthor(ctx, author.OpenLibraryID)
	if err != nil {
		return fmt.Errorf("failed to get author from Open Library: %w", err)
	}

	if olAuthor.Bio != nil {
		// The bio can be a string or a struct with a 'value' field.
		if bioStr, ok := olAuthor.Bio.(string); ok {
			// Find or create the English translation for the bio.
			e.updateBioTranslation(author, bioStr)
		} else if bioMap, ok := olAuthor.Bio.(map[string]interface{}); ok {
			if bioValue, ok := bioMap["value"].(string); ok {
				e.updateBioTranslation(author, bioValue)
			}
		}
	}

	return nil
}

func (e *OpenLibraryAuthorEnricher) updateBioTranslation(author *domain.Author, bio string) {
	// This is a simplified implementation. A real one would need to handle
	// creating or updating a translation record associated with the author.
	// For now, we'll just append it to the author's existing bio if it's empty.
	var bioTranslation *domain.Translation
	for _, t := range author.Translations {
		if t.TranslatableType == "authors" && t.Language == "en" {
			bioTranslation = t
			break
		}
	}

	if bioTranslation == nil {
		author.Translations = append(author.Translations, &domain.Translation{
			Content:          bio,
			Language:         "en",
			TranslatableID:   author.ID,
			TranslatableType: "authors",
		})
	} else {
		if bioTranslation.Content == "" {
			bioTranslation.Content = bio
		}
	}
}