package com.tasteby.controller;

import com.tasteby.security.AuthUtil;
import com.tasteby.service.RestaurantService;
import com.tasteby.service.VideoRelevanceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Set;

/**
 * #356 영상-식당 관련도 LLM 평가 어드민 API.
 * - 미평가 카운트 / 일괄 백필 / 단건 재평가 / 수동 토글
 */
@RestController
@RequestMapping("/api/admin/video-relevance")
public class AdminVideoRelevanceController {

    private static final Logger log = LoggerFactory.getLogger(AdminVideoRelevanceController.class);
    private static final Set<String> VALID = Set.of("strong", "weak", "incidental", "unknown");

    private final RestaurantService restaurantService;
    private final VideoRelevanceService relevanceService;

    public AdminVideoRelevanceController(RestaurantService restaurantService, VideoRelevanceService relevanceService) {
        this.restaurantService = restaurantService;
        this.relevanceService = relevanceService;
    }

    @GetMapping("/pending")
    public Map<String, Object> pendingCount() {
        var admin = AuthUtil.requireAdmin();
        int n = restaurantService.countUnevaluatedLinks();
        log.info("[ADMIN] {} video-relevance pending: {}", admin.getSubject(), n);
        return Map.of("pending", n);
    }

    @PostMapping("/all")
    public Map<String, Object> verifyAll(@RequestParam(defaultValue = "10") int batchSize) {
        var admin = AuthUtil.requireAdmin();
        int pending = restaurantService.countUnevaluatedLinks();
        log.info("[ADMIN] {} triggered video-relevance verifyAllAsync (batchSize={}, pending={})", admin.getSubject(), batchSize, pending);
        // 비동기 트리거 — HTTP request는 즉시 응답. 진행은 /pending 폴링으로 확인.
        relevanceService.verifyAllAsync(batchSize);
        return Map.of("started", true, "pending", pending);
    }

    @PostMapping("/{linkId}/evaluate")
    public Map<String, Object> evaluateOne(@PathVariable String linkId) {
        var admin = AuthUtil.requireAdmin();
        log.info("[ADMIN] {} video-relevance evaluate({})", admin.getSubject(), linkId);
        relevanceService.verify(linkId);
        return Map.of("success", true, "linkId", linkId);
    }

    @PatchMapping("/{linkId}")
    public Map<String, Object> setRelevance(@PathVariable String linkId, @RequestBody Map<String, Object> body) {
        var admin = AuthUtil.requireAdmin();
        Object relObj = body.get("relevance");
        if (!(relObj instanceof String relevance) || !VALID.contains(relevance)) {
            return Map.of("success", false, "error", "relevance must be one of strong|weak|incidental|unknown");
        }
        String reason = body.get("reason") instanceof String s ? s : "manual";
        restaurantService.updateLinkRelevance(linkId, relevance, reason);
        log.info("[ADMIN] {} manual relevance={} for link {}", admin.getSubject(), relevance, linkId);
        return Map.of("success", true, "linkId", linkId, "relevance", relevance);
    }
}
