package com.storycove.service;

import com.storycove.entity.Author;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@ConditionalOnProperty(name = "storycove.search.enabled", havingValue = "true", matchIfMissing = true)
public class AuthorIndexScheduler {

    private static final Logger logger = LoggerFactory.getLogger(AuthorIndexScheduler.class);

    private final AuthorService authorService;
    private final SearchServiceAdapter searchServiceAdapter;

    @Autowired
    public AuthorIndexScheduler(AuthorService authorService, SearchServiceAdapter searchServiceAdapter) {
        this.authorService = authorService;
        this.searchServiceAdapter = searchServiceAdapter;
    }

    @Scheduled(fixedRateString = "${storycove.search.author-reindex-interval:7200000}") // 2 hours default, configurable via SEARCH_AUTHOR_REINDEX_INTERVAL
    public void reindexAllAuthors() {
        try {
            logger.info("Starting scheduled author reindexing...");
            
            List<Author> allAuthors = authorService.findAllWithStories();
            logger.info("Found {} authors to reindex", allAuthors.size());
            
            if (!allAuthors.isEmpty()) {
                searchServiceAdapter.bulkIndexAuthors(allAuthors);
                logger.info("Successfully completed scheduled author reindexing");
            } else {
                logger.info("No authors found to reindex");
            }
            
        } catch (Exception e) {
            logger.error("Failed to complete scheduled author reindexing", e);
        }
    }
    
    // Manual reindex endpoint can be added to AuthorController if needed
}