/**
 * 数据源接口定义
 * 定义所有数据源的标准接口，便于替换和测试
 */

// API 数据源接口
export interface IApiDataSource {
  get<T>(url: string, params?: any): Promise<T>;
  post<T>(url: string, data?: any): Promise<T>;
  put<T>(url: string, data?: any): Promise<T>;
  delete<T>(url: string, data?: any): Promise<T>;
  upload<T>(url: string, file: { uri: string; name: string; type: string }, additionalData?: Record<string, string>): Promise<T>;
}

// 本地数据源接口 (SQLite)
export interface ILocalDataSource {
  query<T>(sql: string, params?: any[]): Promise<T[]>;
  getFirst<T>(sql: string, params?: any[]): Promise<T | null>;
  execute(sql: string, params?: any[]): Promise<void>;
  run(sql: string, params?: any[]): Promise<{ lastInsertRowId: number; changes: number }>;
  transaction(operations: () => Promise<void>): Promise<void>;
  batch(operations: (db: ILocalDataSource) => Promise<void>): Promise<void>;
}

// 缓存数据源接口
export interface ICacheDataSource {
  get<T>(key: string): Promise<T | null>;
  set<T>(key: string, value: T, ttl?: number): Promise<void>;
  delete(key: string): Promise<void>;
  clear(): Promise<void>;
  has(key: string): Promise<boolean>;
  getMultiple<T>(keys: string[]): Promise<(T | null)[]>;
  setMultiple<T>(entries: { key: string; value: T; ttl?: number }[]): Promise<void>;
}

// 数据源错误类型
export class DataSourceError extends Error {
  constructor(
    message: string,
    public code: string,
    public source: string,
    public originalError?: Error
  ) {
    super(message);
    this.name = 'DataSourceError';
  }
}

// 数据源配置
export interface DataSourceConfig {
  api?: {
    baseUrl: string;
    timeout?: number;
    retryCount?: number;
  };
  local?: {
    dbName: string;
    version: number;
  };
  cache?: {
    maxSize: number;
    defaultTtl: number;
  };
}
