package com.erp.ai.controller;

import com.erp.ai.dto.KnowledgeFileRequest;
import com.erp.ai.model.AiKnowledgeFile;
import com.erp.ai.service.AiKnowledgeService;
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;

@RestController
@RequestMapping("/api/ai-knowledge")
@RequiredArgsConstructor
@Slf4j
public class AiKnowledgeController {

    private final AiKnowledgeService aiKnowledgeService;

    @GetMapping
    public ResponseEntity<ApiResponse<List<AiKnowledgeFile>>> list(
            @RequestAttribute(value = "company_code", required = false) String companyCode,
            @RequestAttribute(value = "role", required = false) String role,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String search) {
        boolean isSuper = "SUPER_ADMIN".equals(role);
        String filter = isSuper ? null : companyCode;
        return ResponseEntity.ok(ApiResponse.success(aiKnowledgeService.list(category, filter)));
    }

    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<AiKnowledgeFile>> getById(@PathVariable long id) {
        AiKnowledgeFile file = aiKnowledgeService.getById(id);
        if (file == null) {
            return ResponseEntity.status(404).body(ApiResponse.error("지식 파일을 찾을 수 없습니다."));
        }
        return ResponseEntity.ok(ApiResponse.success(file));
    }

    @PostMapping
    public ResponseEntity<ApiResponse<AiKnowledgeFile>> create(
            @RequestAttribute(value = "user_id", required = false) String userId,
            @RequestAttribute(value = "company_code", required = false) String companyCode,
            @RequestBody KnowledgeFileRequest req) {
        return ResponseEntity.status(201).body(
                ApiResponse.success(
                        aiKnowledgeService.create(req,
                                userId != null ? userId : "system",
                                companyCode != null ? companyCode : "*"),
                        "지식 파일이 등록되었습니다."));
    }

    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<AiKnowledgeFile>> update(
            @PathVariable long id,
            @RequestBody KnowledgeFileRequest req) {
        AiKnowledgeFile updated = aiKnowledgeService.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) {
        aiKnowledgeService.delete(id);
        return ResponseEntity.ok(ApiResponse.success(null, "지식 파일이 삭제되었습니다."));
    }
}
