import { apiClient } from './api';

export interface QueryRequest {
  action: 'list' | 'get' | 'create' | 'update' | 'delete';
  table: string;
  id?: string;
  data?: Record<string, any>;
  filters?: Record<string, any>;
  search?: string;
  search_columns?: string[];
  order_by?: string;
  order_dir?: 'ASC' | 'DESC';
  limit?: number;
  offset?: number;
}

export interface QueryResponse<T = any> {
  data: T;
  error?: string;
}

/**
 * Execute a ResolveSpec query
 */
export async function executeQuery<T = any>(request: QueryRequest): Promise<T> {
  const response = await apiClient.query(request);
  return response as T;
}

/**
 * List records from a table
 */
export async function listRecords<T = any>(
  table: string,
  filters?: Record<string, any>,
  limit?: number,
  offset?: number
): Promise<T[]> {
  return executeQuery<T[]>({
    action: 'list',
    table,
    filters,
    limit,
    offset,
  });
}

/**
 * Get a single record by ID
 */
export async function getRecord<T = any>(table: string, id: string): Promise<T> {
  return executeQuery<T>({
    action: 'get',
    table,
    id,
  });
}

/**
 * Create a new record
 */
export async function createRecord<T = any>(table: string, data: Record<string, any>): Promise<T> {
  return executeQuery<T>({
    action: 'create',
    table,
    data,
  });
}

/**
 * Update an existing record
 */
export async function updateRecord<T = any>(table: string, id: string, data: Record<string, any>): Promise<T> {
  return executeQuery<T>({
    action: 'update',
    table,
    id,
    data,
  });
}

/**
 * Delete a record
 */
export async function deleteRecord(table: string, id: string): Promise<void> {
  await executeQuery({
    action: 'delete',
    table,
    id,
  });
}
