import request from '../utils/request'

// ============================== 数据源 CRUD ==============================

export function getDataSources() {
  return request.get('/kb/datasources')
}

export function getDataSource(id) {
  return request.get(`/kb/datasources/${id}`)
}

export function createDataSource(data) {
  return request.post('/kb/datasources', data)
}

export function updateDataSource(id, data) {
  return request.put(`/kb/datasources/${id}`, data)
}

export function deleteDataSource(id) {
  return request.delete(`/kb/datasources/${id}`)
}

/**
 * 测试连接（不持久化）
 * @param {Object} data 数据源信息（passwordPlain 为明文密码）
 */
export function testDataSource(data) {
  return request.post('/kb/datasources/test', data)
}

/**
 * 测试已存在数据源（持久化结果）
 */
export function testExistingDataSource(id) {
  return request.post(`/kb/datasources/${id}/test`)
}

export function getStructuredRagProfile(id) {
  return request.get(`/kb/datasources/${id}/rag-profile`)
}

export function refreshStructuredRagProfile(id) {
  return request.post(`/kb/datasources/${id}/rag-profile/refresh`)
}

// ============================== SQL Console ==============================

export function getSchemas(datasourceId) {
  return request.get(`/kb/datasources/${datasourceId}/schemas`)
}

export function getTables(datasourceId, schema) {
  const params = schema ? { schema } : {}
  return request.get(`/kb/datasources/${datasourceId}/tables`, { params })
}

export function getTableColumns(datasourceId, table, schema) {
  const params = schema ? { schema } : {}
  return request.get(`/kb/datasources/${datasourceId}/tables/${table}/columns`, { params })
}

export function getTableRowCount(datasourceId, table, schema) {
  const params = schema ? { schema } : {}
  return request.get(`/kb/datasources/${datasourceId}/tables/${table}/count`, { params })
}
export function getTableData(datasourceId, table, schema, limit) {
  const params = {}
  if (schema) params.schema = schema
  if (limit != null) params.limit = limit
  return request.get(`/kb/datasources/${datasourceId}/tables/${table}/data`, { params })
}

/**
 * 执行 SQL 查询
 * @param {number} datasourceId
 * @param {string} sql
 * @param {number|null} limit
 */
export function executeSql(datasourceId, sql, limit) {
  return request.post(`/kb/datasources/${datasourceId}/query`, { sql, limit })
}

export function getQueryHistory(datasourceId, page = 1, size = 20) {
  return request.get(`/kb/datasources/${datasourceId}/history`, { params: { page, size } })
}

export function clearQueryHistory(datasourceId) {
  return request.delete(`/kb/datasources/${datasourceId}/history`)
}
