package com.lingyue.graph.controller;

import com.lingyue.common.domain.AjaxResult;
import com.lingyue.graph.entity.TextStorage;
import com.lingyue.graph.service.TextStorageService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 文本存储控制器
 * 
 * @author lingyue
 * @since 2026-01-14
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/graph")
@RequiredArgsConstructor
@Tag(name = "文本存储", description = "文本存储路径管理接口")
public class TextStorageController {
    
    private final TextStorageService textStorageService;
    
    /**
     * 保存文本存储记录
     * 
     * @param request 请求参数
     * @return 操作结果
     */
    @PostMapping("/text-storage")
    @Operation(summary = "保存文本存储记录", description = "记录TXT文件存储路径到数据库")
    public AjaxResult<TextStorage> saveTextStorage(
            @Parameter(description = "请求参数", required = true)
            @RequestBody Map<String, Object> request) {
        
        String documentId = (String) request.get("documentId");
        String filePath = (String) request.get("filePath");
        
        if (documentId == null || documentId.isEmpty()) {
            return AjaxResult.error("文档ID不能为空", null);
        }
        
        if (filePath == null || filePath.isEmpty()) {
            return AjaxResult.error("文件路径不能为空", null);
        }
        
        try {
            TextStorage textStorage = textStorageService.saveTextStorage(documentId, filePath);
            return AjaxResult.success(textStorage);
        } catch (Exception e) {
            log.error("保存文本存储记录失败: documentId={}, filePath={}", documentId, filePath, e);
            return AjaxResult.error("保存文本存储记录失败: " + e.getMessage(), null);
        }
    }
    
    /**
     * 根据文档ID查询文本存储记录
     * 
     * @param documentId 文档ID
     * @return 文本存储记录
     */
    @GetMapping("/text-storage/{documentId}")
    @Operation(summary = "查询文本存储记录", description = "根据文档ID查询文本存储路径")
    public AjaxResult<TextStorage> getTextStorage(
            @Parameter(description = "文档ID", required = true)
            @PathVariable String documentId) {
        
        TextStorage textStorage = textStorageService.getByDocumentId(documentId);
        if (textStorage == null) {
            return AjaxResult.error("文本存储记录不存在", null);
        }
        
        return AjaxResult.success(textStorage);
    }
}
