package com.storycove.controller;

import com.storycove.entity.Story;
import com.storycove.service.StoryService;
import com.storycove.service.SearchServiceAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/search")
public class SearchController {
    
    private final SearchServiceAdapter searchServiceAdapter;
    private final StoryService storyService;
    
    public SearchController(SearchServiceAdapter searchServiceAdapter, StoryService storyService) {
        this.searchServiceAdapter = searchServiceAdapter;
        this.storyService = storyService;
    }
    
    @PostMapping("/reindex")
    public ResponseEntity<?> reindexAllStories() {
        try {
            List<Story> allStories = storyService.findAll();
            searchServiceAdapter.bulkIndexStories(allStories);
            
            return ResponseEntity.ok(Map.of(
                "message", "Successfully reindexed all stories",
                "storiesCount", allStories.size()
            ));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of(
                "error", "Failed to reindex stories: " + e.getMessage()
            ));
        }
    }
    
    @GetMapping("/health")
    public ResponseEntity<?> searchHealthCheck() {
        try {
            // Search service is operational if it's injected
            return ResponseEntity.ok(Map.of(
                "status", "healthy",
                "message", "Search service is operational"
            ));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of(
                "status", "unhealthy", 
                "error", e.getMessage()
            ));
        }
    }
}