package com.agent.management.controller;

import com.agent.management.common.Result;
import com.agent.management.model.entity.DataSource;
import com.agent.management.service.DataSourceService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 数据源 CRUD API（密码加密、不返回敏感字段）
 */
@RestController
@RequestMapping("/api/kb/datasources")
@RequiredArgsConstructor
@Validated
public class DataSourceController {

    private final DataSourceService dataSourceService;
    private final com.agent.management.rag.structured.StructuredSchemaProfileService structuredProfiles;

    @GetMapping
    public Result<List<DataSource>> list() {
        return Result.success(dataSourceService.listAll());
    }

    @GetMapping("/{id}")
    public Result<DataSource> get(@PathVariable Long id) {
        return Result.success(dataSourceService.get(id));
    }

    @PostMapping
    public Result<DataSource> create(@Valid @RequestBody DataSource ds) {
        DataSource saved = dataSourceService.create(ds);
        structuredProfiles.prewarm(saved.getId());
        return Result.success(saved);
    }

    @PutMapping("/{id}")
    public Result<DataSource> update(@PathVariable Long id, @RequestBody DataSource ds) {
        DataSource saved = dataSourceService.update(id, ds);
        structuredProfiles.refreshAsync(id);
        return Result.success(saved);
    }

    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        structuredProfiles.deleteProfiles(id);
        dataSourceService.delete(id);
        return Result.success(null);
    }

    @GetMapping("/{id}/rag-profile")
    public Result<java.util.Map<String,Object>> ragProfile(@PathVariable Long id) {
        dataSourceService.get(id);
        return Result.success(structuredProfiles.status(id));
    }

    @PostMapping("/{id}/rag-profile/refresh")
    public Result<java.util.Map<String,Object>> refreshRagProfile(@PathVariable Long id) {
        dataSourceService.get(id);
        structuredProfiles.refreshAsync(id);
        return Result.success(structuredProfiles.status(id));
    }

    /**
     * 测试连接（不持久化，可用于新增/编辑前的预检）
     */
    @PostMapping("/test")
    public Result<DataSourceService.TestResult> test(@RequestBody DataSource ds) {
        return Result.success(dataSourceService.testConnection(ds));
    }

    /**
     * 测试已存在数据源（持久化结果到 testStatus/testMessage）
     */
    @PostMapping("/{id}/test")
    public Result<DataSourceService.TestResult> testExisting(@PathVariable Long id) {
        return Result.success(dataSourceService.testExisting(id));
    }
}
