import axios from 'axios';
import { useAppStore } from '../store/useAppStore';

const api = axios.create({
  baseURL: 'http://localhost:8000/api',
});

api.interceptors.request.use((config) => {
  const { connection, activeDatabase } = useAppStore.getState();
  if (connection) {
    config.params = {
      ...config.params,
      host: connection.host,
      username: connection.username,
      password: connection.password,
      port: connection.port,
      database: config.params?.database || activeDatabase || connection.database,
    };
  }
  return config;
});

export default api;

export const SchemaService = {
  getDatabases: () => api.get('/schema/databases'),
  createDatabase: (name: string, charset?: string, collation?: string) => api.post('/schema/databases', { name, charset, collation }),
  getTables: (db: string) => api.get(`/schema/tables/${db}`, { params: { database: db } }),
  getDatabaseMetadata: (db: string) => api.get(`/schema/metadata/${db}`, { params: { database: db } }),
  getTablesMetadata: (db: string) => api.get(`/schema/metadata/${db}/tables`, { params: { database: db } }),
  getTableMetadata: (db: string, table: string) => api.get(`/schema/metadata/${db}/${table}`, { params: { database: db } }),
  getTableSchema: (table: string, database?: string) => api.get(`/schema/${table}`, { params: { database } }),
  getTableData: (table: string, params: any) => api.get(`/schema/${table}/data`, { params }),
  truncateTable: (table: string, database?: string) => api.post(`/schema/truncate/${table}`, { database }),
  dropTable: (table: string, database?: string) => api.post(`/schema/drop/${table}`, { database }),
  optimizeTable: (table: string, database?: string) => api.post(`/schema/optimize/${table}`, { database }),
  bulkAction: (data: { tables: string[], action: string, database: string }) => api.post('/schema/bulk-action', data),
  batchUpdate: (table: string, changes: any[]) => api.post(`/schema/${table}/batch-update`, { changes }),
  executeQuery: (query: string) => api.post('/schema/execute', { query }),
  exportDatabase: (database?: string, table?: string, filters?: any) => api.post('/schema/export', { 
    database, 
    table, 
    filters: filters ? JSON.stringify(filters) : undefined 
  }, { responseType: 'blob' }),
  importDatabase: (formData: FormData) => api.post('/schema/import', formData, {
    headers: { 'Content-Type': 'multipart/form-data' }
  }),
};
