import api from './api'
import { longRunningApi } from './api'
import type { DatabaseConnection, DiscoveredConnection, DbPreset, TableInfo, ColumnInfo, JoinDefinition, SetupStatus, Subscription, NotificationEntry, StatusStage, SyncEvent, WatchColumn, SyncJob } from '../types'

export const configApi = {
  // DB Presets
  getDbPresets: () => api.get<DbPreset[]>('/config/db-presets'),

  // Connections
  listConnections: () => api.get<DatabaseConnection[]>('/config/connections'),
  createConnection: (data: {
    name: string;
    db_type: string;
    source_system?: string;
    connection_string?: string;
    connection_string_template?: string;
    username?: string;
    password?: string;
    host?: string;
    port?: number | string;
    database?: string;
    driver?: string;
    extra_params?: string;
  }) => api.post<DatabaseConnection>('/config/connections', data),
  discoverConnections: (scanNetwork = false) =>
    api.get<DiscoveredConnection[]>('/setup/discover-connections', { params: { scan_network: scanNetwork } }),
  testConnection: (id: string) => api.post(`/config/connections/${id}/test`),
  discoverSchema: (id: string) => longRunningApi.post(`/config/connections/${id}/discover`),
  browseRemoteTables: (id: string, params?: { schema?: string; table?: string; limit?: number }) =>
    longRunningApi.get(`/config/connections/${id}/browse`, { params }),
  registerSelectedTables: (id: string, selections: { schema: string; table: string }[]) =>
    api.post(`/config/connections/${id}/register-tables`, { selections }),
  deleteConnection: (id: string) => api.delete(`/config/connections/${id}`),

  // Tables
  listTables: () => api.get<TableInfo[]>('/config/tables'),
  getTable: (id: string) => api.get<TableInfo>(`/config/tables/${id}`),
  updateTable: (id: string, data: Partial<TableInfo>) => api.put(`/config/tables/${id}`, data),
  deleteTable: (id: string) => api.delete(`/config/tables/${id}`),

  // Columns
  updateColumn: (id: string, data: Partial<ColumnInfo>) => api.put(`/config/columns/${id}`, data),

  // Joins
  listJoins: () => api.get<JoinDefinition[]>('/config/joins'),
  createJoin: (data: any) => api.post('/config/joins', data),
  deleteJoin: (id: string) => api.delete(`/config/joins/${id}`),
  inferJoins: () => api.post('/config/joins/infer'),

  // Audit
  getAuditLog: (limit = 50) => api.get('/config/audit', { params: { limit } }),
  getAuditStats: () => api.get('/config/audit/stats'),

  // Setup
  getSetupStatus: () => api.get<SetupStatus>('/setup/status'),
  listOdbcDsns: () => api.get('/setup/odbc'),
  testOllama: () => api.post('/setup/test-ollama'),
  testClaude: () => api.post('/setup/test-claude'),
  getLogs: (level = 'WARNING', limit = 100) =>
    api.get('/setup/logs', { params: { level, limit } }),

  // Sync — returns immediately with a job_id. Poll getSyncJob() for progress.
  syncTable: (data: { connection_id: string; source_schema: string; source_table: string; local_table?: string }) =>
    api.post<{ job_id: string; status: string; message: string }>('/sync', data),
  listSyncJobs: (limit = 50) =>
    api.get<{ jobs: SyncJob[]; count: number }>('/sync/jobs', { params: { limit } }),
  getSyncJob: (jobId: string) =>
    api.get<SyncJob>(`/sync/jobs/${jobId}`),
  cancelSyncJob: (jobId: string) =>
    api.post(`/sync/jobs/${jobId}/cancel`),

  // Tracking
  searchDocuments: (q: string) => api.get('/tracking/search', { params: { q } }),
  getChain: (chainId: string) => api.get(`/tracking/chain/${chainId}`),
  autoLink: () => api.post('/tracking/auto-link'),

  // Notifications — Subscriptions
  createSubscription: (data: { email: string; doc_number: string; source_system?: string; doc_type?: string; notify_on_stages?: string[] }) =>
    api.post<Subscription>('/notifications/subscriptions', data),
  listSubscriptions: (params?: { email?: string; doc_number?: string }) =>
    api.get<{ subscriptions: Subscription[]; count: number }>('/notifications/subscriptions', { params }),
  updateSubscription: (id: string, data: Partial<Subscription>) =>
    api.put<Subscription>(`/notifications/subscriptions/${id}`, data),
  deleteSubscription: (id: string) => api.delete(`/notifications/subscriptions/${id}`),

  // Notifications — History
  getNotificationHistory: (params?: { limit?: number; status?: string }) =>
    api.get<{ notifications: NotificationEntry[]; count: number }>('/notifications/history', { params }),
  getNotificationHistoryForDoc: (docNumber: string) =>
    api.get<{ notifications: NotificationEntry[]; count: number }>(`/notifications/history/${docNumber}`),

  // Notifications — Stages
  listStages: (params?: { doc_type?: string; source_system?: string }) =>
    api.get<{ stages: StatusStage[]; count: number }>('/notifications/stages', { params }),
  createStage: (data: { doc_type: string; source_system: string; stage_order: number; stage_key: string; stage_label: string }) =>
    api.post<StatusStage>('/notifications/stages', data),
  deleteStage: (id: string) => api.delete(`/notifications/stages/${id}`),

  // Notifications — Watch Columns
  getWatchColumns: (tableId: string) =>
    api.get<{ columns: WatchColumn[]; count: number }>(`/notifications/watch-columns/${tableId}`),
  configureWatchColumns: (data: { table_id: string; columns: { column_name: string; is_status_column: boolean; is_key_column: boolean; is_doc_number_column?: boolean }[] }) =>
    api.post('/notifications/watch-columns', data),

  // Notifications — Settings
  getNotificationSettings: () => api.get('/notifications/settings'),
  updateNotificationSettings: (key: string, value: Record<string, any>) =>
    api.put('/notifications/settings', { key, value }),
  sendTestEmail: (email: string) => api.post('/notifications/test-email', { email }),
  triggerNotificationProcessing: () => api.post('/notifications/process'),

  // Notifications — Events (debug)
  getSyncEvents: (params?: { limit?: number; table_id?: string }) =>
    api.get<{ events: SyncEvent[]; count: number }>('/notifications/events', { params }),

  // Notifications — Chain status
  getChainStatus: (docNumber: string) =>
    api.get(`/notifications/chain-status/${docNumber}`),

  // Overview
  getConfigOverview: () => api.get('/config/overview'),

  // Domain Knowledge
  getDomainKnowledge: () => api.get<{ items: string[] }>('/config/domain-knowledge'),
  updateDomainKnowledge: (items: string[]) => api.put('/config/domain-knowledge', { items }),

  // Maintenance
  cleanupStalePatterns: () => api.post<{ deleted: number; details: string[] }>('/config/cleanup-patterns'),
  enrichTable: (tableId: string) => api.post<{ enriched: number }>(`/config/tables/${tableId}/enrich`),
}
