import client from '../client';

export interface AdbTableDef {
  id: string;
  table_name: string;
  description?: string;
  is_active: boolean;
}

export interface AdbConfigFull {
  id: string;
  config_name: string;
  dsn: string;
  username: string;
  table_name?: string;
  use_mtls: boolean;
  is_active: boolean;
  wallet_dir?: string;
  genai_config_id?: string;
  embedding_model_id?: string;
  tables?: AdbTableDef[];
  created_at?: string;
}

export interface AdbTestResult {
  status: 'success' | 'error';
  message: string;
}

export interface WalletParseResult {
  dsn_names: string[];
  files: string[];
}

export const adbApi = {
  list: () =>
    client.get('/adb/configs') as unknown as Promise<AdbConfigFull[]>,

  create: (fd: FormData) =>
    client.post('/adb/config', fd, { headers: { 'Content-Type': 'multipart/form-data' } }) as unknown as Promise<{ id: string; config_name: string }>,

  update: (id: string, fd: FormData) =>
    client.put(`/adb/configs/${id}`, fd, { headers: { 'Content-Type': 'multipart/form-data' } }) as unknown as Promise<{ id: string; config_name: string }>,

  remove: (id: string) =>
    client.delete(`/adb/configs/${id}`) as unknown as Promise<{ ok: boolean }>,

  test: (id: string) =>
    client.post(`/adb/test/${id}`) as unknown as Promise<AdbTestResult>,

  parseWallet: (file: File) => {
    const fd = new FormData();
    fd.append('wallet', file);
    return client.post('/adb/parse-wallet', fd, { headers: { 'Content-Type': 'multipart/form-data' } }) as unknown as Promise<WalletParseResult>;
  },

  uploadWallet: (id: string, file: File) => {
    const fd = new FormData();
    fd.append('wallet', file);
    return client.post(`/adb/${id}/upload-wallet`, fd, { headers: { 'Content-Type': 'multipart/form-data' } }) as unknown as Promise<{ ok: boolean; files: string[] }>;
  },

  addTable: (vid: string, tableName: string, description: string) =>
    client.post(`/adb/${vid}/tables`, { table_name: tableName, description }) as unknown as Promise<{ id: string }>,

  updateTable: (vid: string, tid: string, body: { table_name?: string; description?: string; is_active?: boolean }) =>
    client.put(`/adb/${vid}/tables/${tid}`, body) as unknown as Promise<{ ok: boolean }>,

  removeTable: (vid: string, tid: string) =>
    client.delete(`/adb/${vid}/tables/${tid}`) as unknown as Promise<{ ok: boolean }>,
};
