package com.zioinfo.kintex.work.search;

import com.zioinfo.kintex.auth.EventAccessGuard;
import com.zioinfo.kintex.auth.KintexPrincipal;
import com.zioinfo.kintex.common.ApiResponse;
import jakarta.validation.Valid;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/** 통합검색 API (/api/work/search). 인증 사용자. 키워드(GET) + 자연어 AI(POST). */
@RestController
@RequestMapping("/api/work/search")
public class SearchController {

    private final SearchService service;
    private final SearchAiService aiService;
    private final EventAccessGuard guard;

    public SearchController(SearchService service, SearchAiService aiService, EventAccessGuard guard) {
        this.service = service;
        this.aiService = aiService;
        this.guard = guard;
    }

    @GetMapping
    public ApiResponse<List<SearchResultItem>> search(@AuthenticationPrincipal KintexPrincipal principal,
                                                      @RequestParam("q") String q,
                                                      @RequestParam(defaultValue = "30") int limit) {
        guard.require(principal);
        return ApiResponse.ok(service.search(principal, q, limit));
    }

    /** G-07 자연어 통합검색 — 질문을 AI 로 구조화 후 키워드 검색 조합 + 근거 요약. AI 불가 시 키워드 검색 강등. */
    @PostMapping("/ai")
    public ApiResponse<AiSearchResult> aiSearch(@AuthenticationPrincipal KintexPrincipal principal,
                                                @Valid @RequestBody AiSearchRequest req) {
        guard.require(principal);
        int limit = req.limit() == null ? 30 : req.limit();
        return ApiResponse.ok(aiService.search(principal, req.q(), limit));
    }
}
