package com.lingyue.graph.controller;

import com.lingyue.common.domain.AjaxResult;
import com.lingyue.graph.dto.*;
import com.lingyue.graph.entity.DataSource;
import com.lingyue.graph.service.DataSourceService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

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

/**
 * 数据源控制器
 * 
 * @author lingyue
 * @since 2026-01-21
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/datasource")
@RequiredArgsConstructor
@Tag(name = "数据源管理", description = "数据源 CRUD 和取值接口")
public class DataSourceController {
    
    private final DataSourceService dataSourceService;
    
    // 临时用户ID，实际应从安全上下文获取
    private static final String DEFAULT_USER_ID = "default-user";
    
    /**
     * 创建数据源
     */
    @PostMapping
    @Operation(summary = "创建数据源", description = "创建新的数据源并绑定节点")
    public AjaxResult<DataSource> create(
            @RequestBody @Valid CreateDataSourceRequest request,
            @RequestHeader(value = "X-User-Id", required = false) String userId) {
        
        String actualUserId = userId != null ? userId : DEFAULT_USER_ID;
        DataSource dataSource = dataSourceService.create(actualUserId, request);
        return AjaxResult.success(dataSource);
    }
    
    /**
     * 获取数据源
     */
    @GetMapping("/{id}")
    @Operation(summary = "获取数据源", description = "根据ID获取数据源详情")
    public AjaxResult<?> getById(
            @PathVariable @Parameter(description = "数据源ID") String id) {
        
        DataSource dataSource = dataSourceService.getById(id);
        if (dataSource == null) {
            return AjaxResult.error("数据源不存在: " + id);
        }
        return AjaxResult.success(dataSource);
    }
    
    /**
     * 按文档查询数据源
     */
    @GetMapping("/document/{documentId}")
    @Operation(summary = "按文档查询", description = "获取指定文档的所有数据源")
    public AjaxResult<List<DataSource>> getByDocumentId(
            @PathVariable @Parameter(description = "文档ID") String documentId) {
        
        List<DataSource> dataSources = dataSourceService.getByDocumentId(documentId);
        return AjaxResult.success(dataSources);
    }
    
    /**
     * 按用户查询数据源
     */
    @GetMapping("/user/{userId}")
    @Operation(summary = "按用户查询", description = "获取指定用户的所有数据源")
    public AjaxResult<List<DataSource>> getByUserId(
            @PathVariable @Parameter(description = "用户ID") String userId) {
        
        List<DataSource> dataSources = dataSourceService.getByUserId(userId);
        return AjaxResult.success(dataSources);
    }
    
    /**
     * 按用户和类型查询
     */
    @GetMapping("/user/{userId}/type/{type}")
    @Operation(summary = "按用户和类型查询", description = "获取指定用户指定类型的数据源")
    public AjaxResult<List<DataSource>> getByUserIdAndType(
            @PathVariable @Parameter(description = "用户ID") String userId,
            @PathVariable @Parameter(description = "数据源类型") String type) {
        
        List<DataSource> dataSources = dataSourceService.getByUserIdAndType(userId, type);
        return AjaxResult.success(dataSources);
    }
    
    /**
     * 更新数据源
     */
    @PutMapping("/{id}")
    @Operation(summary = "更新数据源", description = "更新数据源基本信息")
    public AjaxResult<?> update(
            @PathVariable @Parameter(description = "数据源ID") String id,
            @RequestBody UpdateDataSourceRequest request) {
        
        try {
            DataSource dataSource = dataSourceService.update(id, request);
            return AjaxResult.success(dataSource);
        } catch (IllegalArgumentException e) {
            return AjaxResult.error(e.getMessage());
        }
    }
    
    /**
     * 更新节点引用
     */
    @PutMapping("/{id}/refs")
    @Operation(summary = "更新节点引用", description = "更新数据源绑定的节点引用（支持替换/追加/移除）")
    public AjaxResult<?> updateRefs(
            @PathVariable @Parameter(description = "数据源ID") String id,
            @RequestBody UpdateRefsRequest request) {
        
        try {
            DataSource dataSource = dataSourceService.updateRefs(id, request);
            return AjaxResult.success(dataSource);
        } catch (IllegalArgumentException e) {
            return AjaxResult.error(e.getMessage());
        }
    }
    
    /**
     * 删除数据源
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除数据源", description = "删除指定数据源")
    public AjaxResult<?> delete(
            @PathVariable @Parameter(description = "数据源ID") String id) {
        
        dataSourceService.delete(id);
        return AjaxResult.success();
    }
    
    /**
     * 获取数据源值（核心接口）
     */
    @GetMapping("/{id}/value")
    @Operation(summary = "获取数据源值", description = "从绑定的节点中提取并聚合值")
    public AjaxResult<?> getValue(
            @PathVariable @Parameter(description = "数据源ID") String id) {
        
        try {
            DataSourceValue value = dataSourceService.getValue(id);
            return AjaxResult.success(value);
        } catch (IllegalArgumentException e) {
            return AjaxResult.error(e.getMessage());
        }
    }
    
    /**
     * 批量获取数据源值
     */
    @PostMapping("/batch-value")
    @Operation(summary = "批量获取数据源值", description = "批量获取多个数据源的值，用于模板渲染")
    public AjaxResult<Map<String, DataSourceValue>> batchGetValue(
            @RequestBody BatchValueRequest request) {
        
        Map<String, DataSourceValue> values = dataSourceService.batchGetValue(request.getDataSourceIds());
        return AjaxResult.success(values);
    }
}
