package com.hertz.modules.knowledge.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hertz.common.api.ApiResponse;
import com.hertz.modules.knowledge.entity.KnowledgeBase;
import com.hertz.modules.knowledge.entity.KnowledgeDocument;
import com.hertz.modules.knowledge.service.KnowledgeBaseService;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/api/knowledge-bases")
@RequiredArgsConstructor
public class KnowledgeBaseController {

    private final KnowledgeBaseService knowledgeBaseService;

    @PostMapping
    public ApiResponse<KnowledgeBase> createKnowledgeBase(@RequestBody KnowledgeBase kb) {
        return ApiResponse.ok(knowledgeBaseService.createKnowledgeBase(kb.getName(), kb.getDescription()));
    }

    @GetMapping
    public ApiResponse<IPage<KnowledgeBase>> page(
        @RequestParam(defaultValue = "1") @Min(1) int page,
        @RequestParam(defaultValue = "10") @Min(1) @Max(200) int size,
        @RequestParam(required = false) String keyword
    ) {
        return ApiResponse.ok(knowledgeBaseService.pageKnowledgeBases(page, size, keyword));
    }

    @PostMapping("/{id}/upload")
    public ApiResponse<Void> uploadDocument(@PathVariable Long id, @RequestParam("file") MultipartFile file) {
        knowledgeBaseService.uploadDocument(id, file);
        return ApiResponse.ok();
    }

    @GetMapping("/{id}/documents")
    public ApiResponse<List<KnowledgeDocument>> listDocuments(@PathVariable Long id) {
        return ApiResponse.ok(knowledgeBaseService.listDocuments(id));
    }

    @DeleteMapping("/{id}/documents/{docId}")
    public ApiResponse<Void> deleteDocument(@PathVariable Long id, @PathVariable Long docId) {
        knowledgeBaseService.deleteDocument(id, docId);
        return ApiResponse.ok();
    }

    @PostMapping("/{id}/rebuild")
    public ApiResponse<Void> rebuild(@PathVariable Long id) {
        knowledgeBaseService.rebuildVectorStore(id);
        return ApiResponse.ok();
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteKnowledgeBase(@PathVariable Long id) {
        knowledgeBaseService.deleteKnowledgeBase(id);
        return ApiResponse.ok();
    }
}
