package com.zioinfo.kintex.work.search;

import com.zioinfo.kintex.auth.KintexPrincipal;
import com.zioinfo.kintex.system.SystemAccessGuard;
import org.springframework.stereotype.Service;

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

/** 통합검색 서비스 — 공통 업무 데이터를 가로질러 title 검색. DataScope 적용. */
@Service
public class SearchService {

    private final SearchMapper mapper;
    private final SystemAccessGuard scope;

    public SearchService(SearchMapper mapper, SystemAccessGuard scope) {
        this.mapper = mapper;
        this.scope = scope;
    }

    public List<SearchResultItem> search(KintexPrincipal principal, String q, int limit) {
        if (q == null || q.isBlank()) {
            return List.of();
        }
        int size = limit <= 0 ? 30 : Math.min(limit, 100);
        boolean seeAll = scope.canSeeAll(principal);
        List<Map<String, Object>> rows = mapper.searchAll(q.trim(), principal.userId(), seeAll, size);
        return rows.stream().map(r -> {
            String type = str(r.get("type"));
            String id = str(r.get("id"));
            return new SearchResultItem(type, id, str(r.get("title")), str(r.get("createdAt")), routeFor(type, id));
        }).toList();
    }

    /** type(+id)별 프론트 이동 경로 파생. 도메인 크로스검색 결과의 클릭 내비게이션용. */
    private static String routeFor(String type, String id) {
        if (type == null) {
            return null;
        }
        return switch (type) {
            case "WORKLOG" -> "/work/worklog";
            case "NOTICE" -> "/work/notice";
            case "MEETING" -> "/work/meeting";
            case "REPORT" -> "/work/report";
            case "OPINION" -> "/work/opinion";
            case "EVENT" -> "/schedule";
            case "COMPANY" -> "/admin/companies";
            case "AUCTION" -> id == null ? "/auctions" : "/auctions/" + id;
            case "BOOTH" -> "/booth-sales";
            case "LEAD" -> "/leads";
            case "CMS" -> "/cms";
            default -> null;
        };
    }

    private static String str(Object o) { return o == null ? null : String.valueOf(o); }
}
