package com.zioinfo.mall.cs;

import com.zioinfo.mall.ai.MallAiService;
import com.zioinfo.mall.common.ApiResponse;
import com.zioinfo.mall.cs.mapper.CsMapper;
import com.zioinfo.mall.integration.ItsmClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

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

/**
 * 고객문의 API — /api/mall/cs.
 * 문의 등록 시 ITSM SR 자동 생성 + Ollama AI 자동응답 초안 작성(Java 폴백).
 */
@Slf4j
@RestController
@RequestMapping("/api/mall/cs")
@RequiredArgsConstructor
public class CsController {

    private final CsMapper mapper;
    private final ItsmClient itsmClient;
    private final MallAiService aiService;

    @GetMapping
    public ApiResponse<List<MallCsTicket>> mine(Authentication auth) {
        return ApiResponse.ok(mapper.findByOwner(auth.getName()));
    }

    @GetMapping("/admin")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<List<MallCsTicket>> all(@RequestParam(required = false) String status) {
        return ApiResponse.ok(mapper.findAll(status));
    }

    /** 문의 등록 → ITSM SR 생성 + AI 자동응답. */
    @PostMapping
    public ApiResponse<MallCsTicket> create(@RequestBody MallCsTicket t, Authentication auth) {
        t.setOwner(auth.getName());
        mapper.insert(t);
        // ITSM SR 자동 생성 (실패 무시)
        try {
            String srId = itsmClient.createSr("[Mall CS] " + t.getSubject(),
                    t.getContent(), "MEDIUM");
            if (srId != null) mapper.setSr(t.getId(), srId);
        } catch (Exception e) {
            log.warn("CS→ITSM SR 생성 실패(무시): {}", e.getMessage());
        }
        // AI 자동응답 초안
        try {
            String reply = aiService.csAutoReply(t.getSubject(), t.getContent());
            if (reply != null && !reply.isBlank()) mapper.setAiReply(t.getId(), reply);
        } catch (Exception e) {
            log.warn("CS AI 자동응답 실패(무시): {}", e.getMessage());
        }
        return ApiResponse.ok(mapper.findById(t.getId()));
    }

    @PutMapping("/{id}/status")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<MallCsTicket> status(@PathVariable Long id, @RequestBody Map<String, String> req) {
        mapper.updateStatus(id, req.getOrDefault("status", "CLOSED"));
        return ApiResponse.ok(mapper.findById(id));
    }
}
