package com.tasteby.controller;

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

import java.util.Map;

/**
 * #322 LLM 검증 어드민 API.
 * - hidden 토글
 * - 일괄 백필
 */
@RestController
@RequestMapping("/api/admin/restaurants")
public class AdminRestaurantController {

    private static final Logger log = LoggerFactory.getLogger(AdminRestaurantController.class);

    private final RestaurantService restaurantService;
    private final RestaurantVerifyService verifyService;

    public AdminRestaurantController(RestaurantService restaurantService, RestaurantVerifyService verifyService) {
        this.restaurantService = restaurantService;
        this.verifyService = verifyService;
    }

    /**
     * 어드민용 검증 안 된 식당 수 조회.
     */
    @GetMapping("/verify/pending")
    public Map<String, Object> pendingCount() {
        var admin = AuthUtil.requireAdmin();
        int n = restaurantService.countUnverified();
        log.info("[ADMIN] {} pending verify count: {}", admin.getSubject(), n);
        return Map.of("pending", n);
    }

    /**
     * 어드민용 일괄 백필 트리거. 한 번 호출에 모든 미검증 식당을 처리.
     * 비동기/SSE 없이 동기 응답이라 호출자는 결과까지 기다려야 함(LLM × N).
     */
    @PostMapping("/verify/all")
    public Map<String, Object> verifyAll(@RequestParam(defaultValue = "10") int batchSize) {
        var admin = AuthUtil.requireAdmin();
        log.info("[ADMIN] {} triggered verifyAll(batchSize={})", admin.getSubject(), batchSize);
        int processed = verifyService.verifyAll(batchSize);
        return Map.of("processed", processed);
    }

    /**
     * 어드민용 단건 재검증.
     */
    @PostMapping("/{id}/verify")
    public Map<String, Object> verifyOne(@PathVariable String id) {
        var admin = AuthUtil.requireAdmin();
        log.info("[ADMIN] {} verifyOne({})", admin.getSubject(), id);
        verifyService.verify(id);
        return Map.of("success", true, "id", id);
    }

    // #359 1단계 — google_place_id 중복 조회 (정리/UNIQUE는 후속).
    @GetMapping("/duplicates/place-id")
    public Map<String, Object> duplicatePlaceIds() {
        var admin = AuthUtil.requireAdmin();
        var groups = restaurantService.findDuplicatePlaceIdGroups();
        log.info("[ADMIN] {} duplicate place_id groups: {}", admin.getSubject(), groups.size());
        return Map.of("groups", groups, "group_count", groups.size());
    }

    /**
     * 어드민용 hidden 토글.
     */
    @PatchMapping("/{id}/hidden")
    public Map<String, Object> setHidden(@PathVariable String id, @RequestBody Map<String, Object> body) {
        var admin = AuthUtil.requireAdmin();
        boolean hidden = Boolean.TRUE.equals(body.get("hidden"));
        String reason = body.get("reason") instanceof String s ? s : "manual";
        if (hidden) {
            restaurantService.markHidden(id, reason);
        } else {
            restaurantService.clearHidden(id);
        }
        log.info("[ADMIN] {} set hidden={} for {}", admin.getSubject(), hidden, id);
        return Map.of("success", true, "id", id, "hidden", hidden);
    }
}
