package top.imwork.assist.generator.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import top.imwork.assist.generator.config.DataSourceProperties;
import top.imwork.assist.generator.config.DynamicDataSourceManager;

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

/**
 * Copyright (C), 2015-2025
 * FileName: DataSourceController
 * Author<作者姓名>:   silos
 * CreateTime<创建时间>:   2025/11/9 20:24
 * UpdateTime<修改时间>:   2025/11/9 20:24
 * Description〈功能简述〉: 控制器示例
 * History<历史描述>:
 * Since<版本号>: 1.0.0
 */
@RestController
@RequestMapping("/api/datasource")
public class DataSourceController {

    @Autowired
    private DynamicDataSourceManager dataSourceManager;

    /**
     * 添加动态数据源
     */
    @PostMapping("/add")
    public ResponseEntity<String> addDataSource(@RequestBody DataSourceProperties properties) {
        try {
            String dataSourceKey = generateDataSourceKey(properties);
            dataSourceManager.addDataSource(dataSourceKey, properties);
            return ResponseEntity.ok("数据源添加成功: " + dataSourceKey);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("数据源添加失败: " + e.getMessage());
        }
    }

    /**
     * 使用动态数据源查询
     */
    @PostMapping("/query")
    public ResponseEntity<List<Map<String, Object>>> queryWithDataSource(
            @RequestParam String dataSourceKey,
            @RequestBody String sql) {
        try {
            JdbcTemplate jdbcTemplate = dataSourceManager.getJdbcTemplate(dataSourceKey);
            List<Map<String, Object>> result = jdbcTemplate.queryForList(sql);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(null);
        }
    }

    private String generateDataSourceKey(DataSourceProperties properties) {
        return properties.getUrl().hashCode() + "_" + System.currentTimeMillis();
    }
}