package com.erp.ai.controller;

import com.erp.ai.dto.AgentRequest;
import com.erp.ai.model.AiAgent;
import com.erp.ai.service.AiAgentService;
import com.erp.dto.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/api/ai-agents")
@RequiredArgsConstructor
@Slf4j
public class AiAgentController {

    private final AiAgentService aiAgentService;

    @GetMapping
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> list(
            @RequestAttribute(value = "company_code", required = false) String companyCode,
            @RequestAttribute(value = "role", required = false) String role,
            @RequestParam(required = false) String status,
            @RequestParam(value = "company_code", required = false) String companyCodeParam,
            @RequestParam(required = false) String search) {
        boolean isSuper = "SUPER_ADMIN".equals(role);
        String filter = ("*".equals(companyCodeParam) || isSuper)
                ? null
                : (companyCodeParam != null ? companyCodeParam : companyCode);
        return ResponseEntity.ok(ApiResponse.success(aiAgentService.list(status, filter, search)));
    }

    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getById(@PathVariable long id) {
        Map<String, Object> agent = aiAgentService.getById(id);
        if (agent == null) {
            return ResponseEntity.status(404).body(ApiResponse.error("에이전트를 찾을 수 없습니다."));
        }
        return ResponseEntity.ok(ApiResponse.success(agent));
    }

    @PostMapping
    public ResponseEntity<ApiResponse<AiAgent>> create(
            @RequestAttribute(value = "user_id", required = false) String userId,
            @RequestBody AgentRequest req) {
        return ResponseEntity.status(201).body(
                ApiResponse.success(aiAgentService.create(req, userId != null ? userId : "system"),
                        "에이전트가 생성되었습니다."));
    }

    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<AiAgent>> update(
            @PathVariable long id,
            @RequestBody AgentRequest req) {
        AiAgent updated = aiAgentService.update(id, req);
        if (updated == null) {
            return ResponseEntity.status(404).body(ApiResponse.error("에이전트를 찾을 수 없습니다."));
        }
        return ResponseEntity.ok(ApiResponse.success(updated, "에이전트가 수정되었습니다."));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> delete(@PathVariable long id) {
        aiAgentService.delete(id);
        return ResponseEntity.ok(ApiResponse.success(null, "에이전트가 삭제되었습니다."));
    }
}
