package com.agent.management.controller;

import com.agent.management.common.Result;
import com.agent.management.model.entity.SqlQueryHistory;
import com.agent.management.repository.SqlQueryHistoryRepository;
import com.agent.management.service.SchemaExplorerService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * SQL Console 查询 API
 */
@RestController
@RequestMapping("/api/kb/datasources/{datasourceId}")
@RequiredArgsConstructor
public class DataSourceQueryController {

    private final SchemaExplorerService schemaExplorer;
    private final SqlQueryHistoryRepository historyRepository;

    @GetMapping("/schemas")
    public Result<List<String>> schemas(@PathVariable Long datasourceId) {
        return Result.success(schemaExplorer.listSchemas(datasourceId));
    }

    @GetMapping("/tables")
    public Result<List<SchemaExplorerService.TableSummary>> tables(
            @PathVariable Long datasourceId,
            @RequestParam(required = false) String schema) {
        return Result.success(schemaExplorer.listTables(datasourceId, schema));
    }

    @GetMapping("/tables/{table}/columns")
    public Result<List<SchemaExplorerService.ColumnSpec>> columns(
            @PathVariable Long datasourceId,
            @RequestParam(required = false) String schema,
            @PathVariable String table) {
        return Result.success(schemaExplorer.describeTable(datasourceId, schema, table));
    }

    @GetMapping("/tables/{table}/count")
    public Result<Long> count(
            @PathVariable Long datasourceId,
            @RequestParam(required = false) String schema,
            @PathVariable String table) {
        return Result.success(schemaExplorer.countRows(datasourceId, schema, table));
    }

    /**
     * 预览表数据（自动生成安全 SELECT，可限制行数）
     */
    @GetMapping("/tables/{table}/data")
    public Result<SchemaExplorerService.QueryResult> previewTableData(
            @PathVariable Long datasourceId,
            @PathVariable String table,
            @RequestParam(required = false) String schema,
            @RequestParam(required = false, defaultValue = "100") Integer limit) {
        return Result.success(schemaExplorer.previewTableData(datasourceId, schema, table, limit));
    }

    /**
     * 执行白名单 SQL 查询
     */
    @PostMapping("/query")
    public Result<SchemaExplorerService.QueryResult> query(
            @PathVariable Long datasourceId,
            @RequestBody QueryRequest req) {
        return Result.success(schemaExplorer.executeQuery(
                datasourceId, req.getSql(), req.getLimit()));
    }

    /**
     * 查询历史（分页）
     */
    @GetMapping("/history")
    public Result<Page<SqlQueryHistory>> history(
            @PathVariable Long datasourceId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size) {
        PageRequest pageable = PageRequest.of(Math.max(0, page - 1), Math.max(1, size));
        return Result.success(historyRepository.findByDatasourceIdOrderByExecutedAtDesc(datasourceId, pageable));
    }

    /**
     * 清空数据源的查询历史
     */
    @DeleteMapping("/history")
    public Result<Void> clearHistory(@PathVariable Long datasourceId) {
        historyRepository.deleteByDatasourceId(datasourceId);
        return Result.success(null);
    }

    @Data
    public static class QueryRequest {
        private String sql;
        private Integer limit;
    }
}
