package com.zioinfo.mall.ai;

import com.zioinfo.mall.analytics.mapper.AnalyticsMapper;
import com.zioinfo.mall.common.ApiResponse;
import com.zioinfo.mall.product.MallProduct;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

/**
 * GUARDiA Mall AI API — /api/mall/ai. Ollama 온프레미스 + Java 폴백.
 * 고객용(추천·리뷰요약·자연어검색·카드메시지)과 운영용(당일소진·수요예측·이양추천) 분리.
 */
@RestController
@RequestMapping("/api/mall/ai")
@RequiredArgsConstructor
public class MallAiController {

    private final MallAiService aiService;
    private final AnalyticsMapper analyticsMapper;

    /** 1. 상품 추천 — 공개(스토어프론트). */
    @GetMapping("/recommend")
    public ApiResponse<List<MallProduct>> recommend(@RequestParam(required = false) String occasion,
                                                    @RequestParam(required = false) String keyword,
                                                    @RequestParam(defaultValue = "6") int limit) {
        return ApiResponse.ok(aiService.recommend(occasion, keyword, limit));
    }

    /** 2. 리뷰 AI 요약 — 공개. */
    @GetMapping("/review-summary/{productId}")
    public ApiResponse<Map<String, Object>> reviewSummary(@PathVariable Long productId) {
        return ApiResponse.ok(aiService.summarizeReviews(productId));
    }

    /** 3. 자연어 상품 검색 — 공개. */
    @PostMapping("/nl-search")
    public ApiResponse<Map<String, Object>> nlSearch(@RequestBody Map<String, String> req) {
        return ApiResponse.ok(aiService.nlSearch(req.getOrDefault("query", "")));
    }

    /** 4. CS 자동응답 초안 — 인증 고객. */
    @PostMapping("/cs-reply")
    public ApiResponse<Map<String, Object>> csReply(@RequestBody Map<String, String> req) {
        String reply = aiService.csAutoReply(req.getOrDefault("subject", ""), req.getOrDefault("content", ""));
        return ApiResponse.ok(Map.of("reply", reply));
    }

    /** 7. AI 카드 메시지 — 인증 고객. */
    @PostMapping("/card-message")
    public ApiResponse<Map<String, Object>> cardMessage(@RequestBody Map<String, String> req) {
        List<String> msgs = aiService.cardMessages(req.get("occasion"), req.get("tone"), req.get("recipient"));
        return ApiResponse.ok(Map.of("messages", msgs));
    }

    /** 5. 당일 재고 소진 추천 — MANAGER+. */
    @GetMapping("/daily-clearance/{storeId}")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<Map<String, Object>> dailyClearance(@PathVariable Long storeId) {
        return ApiResponse.ok(aiService.dailyClearanceBouquet(storeId));
    }

    /** 6. 피크시즌 수요 예측 — MANAGER+. */
    @GetMapping("/demand-forecast")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<Map<String, Object>> demandForecast(@RequestParam(defaultValue = "valentine") String season,
                                                           @RequestParam(defaultValue = "14") int days) {
        return ApiResponse.ok(aiService.demandForecast(season, analyticsMapper.salesByStore(days)));
    }

    /** 8. 매장간 재고 이양 추천 — MANAGER+. */
    @PostMapping("/transfer-recommend")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    @SuppressWarnings("unchecked")
    public ApiResponse<List<Map<String, Object>>> transferRecommend(@RequestBody Map<String, Object> req) {
        List<Object> raw = (List<Object>) req.getOrDefault("storeIds", List.of());
        List<Long> storeIds = raw.stream().map(o -> Long.valueOf(String.valueOf(o))).toList();
        return ApiResponse.ok(aiService.transferRecommendations(storeIds));
    }
}
