// 数据源工厂
import { IDataSource, IMockDataSource } from '@/types/datasource';

// 是否使用Mock数据
const useMock = process.env.REACT_APP_USE_MOCK === 'true' || process.env.NODE_ENV === 'development';

/**
 * 基础数据源类
 * 提供通用的数据源方法实现
 */
export class BaseDataSource<T, P = any> implements IDataSource<T, P> {
  protected baseUrl: string;

  constructor(baseUrl: string) {
    this.baseUrl = baseUrl;
  }

  async list(): Promise<T[]> {
    // 这里应该调用实际的API
    return [];
  }

  async detail(id: string): Promise<T> {
    // 这里应该调用实际的API
    throw new Error('Not implemented');
  }

  async create(data: Partial<T>): Promise<T> {
    // 这里应该调用实际的API
    throw new Error('Not implemented');
  }

  async update(id: string, data: Partial<T>): Promise<T> {
    // 这里应该调用实际的API
    throw new Error('Not implemented');
  }

  async delete(id: string): Promise<void> {
    // 这里应该调用实际的API
    throw new Error('Not implemented');
  }

  // 构建查询参数
  protected buildQueryParams(params?: P): string {
    if (!params) return '';
    
    const queryParts = [];
    for (const [key, value] of Object.entries(params)) {
      if (value !== undefined && value !== null) {
        queryParts.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
      }
    }
    
    return queryParts.join('&');
  }
}

/**
 * 基础Mock数据源类
 * 提供通用的Mock数据实现
 */
export class BaseMockDataSource<T, P = any> implements IMockDataSource<T> {
  protected mockData: T[] = [];

  reset(): void {
    this.mockData = [];
  }

  getMockData(): T[] {
    return this.mockData;
  }

  async list(): Promise<T[]> {
    return this.mockData;
  }

  async detail(id: string): Promise<T> {
    const item = this.mockData.find((item: any) => item.id === id);
    if (!item) {
      throw new Error('Item not found');
    }
    return item;
  }

  async create(data: Partial<T>): Promise<T> {
    const newItem = {
      id: `${this.mockData.length + 1}`,
      ...data
    } as T;
    this.mockData.push(newItem);
    return newItem;
  }

  async update(id: string, data: Partial<T>): Promise<T> {
    const index = this.mockData.findIndex((item: any) => item.id === id);
    if (index === -1) {
      throw new Error('Item not found');
    }
    this.mockData[index] = {
      ...this.mockData[index],
      ...data
    };
    return this.mockData[index];
  }

  async delete(id: string): Promise<void> {
    const index = this.mockData.findIndex((item: any) => item.id === id);
    if (index === -1) {
      throw new Error('Item not found');
    }
    this.mockData.splice(index, 1);
  }

  // 延迟方法，用于模拟网络延迟
  protected async delay(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}

/**
 * 数据源工厂类
 * 用于创建数据源实例，根据环境自动切换Mock和真实API
 */
export class DataSourceFactory {
  /**
   * 创建基础 DataSource 实例
   * @param apiDataSource API实现类
   * @param mockDataSource Mock实现类
   * @returns DataSource 实例
   */
  static create<T, P = any>(
    apiDataSource: new () => IDataSource<T, P>,
    mockDataSource: new () => IDataSource<T, P>
  ): IDataSource<T, P> {
    return useMock ? new mockDataSource() : new apiDataSource();
  }

  /**
   * 创建带有自定义方法的 DataSource 实例
   * @param apiDataSource API实现类
   * @param mockDataSource Mock实现类
   * @returns DataSource 实例
   */
  static createWithMethods<T, M extends Record<string, any>, P = any>({
    apiDataSource,
    mockDataSource,
  }: {
    apiDataSource: new () => IDataSource<T, P> & M;
    mockDataSource: new () => IDataSource<T, P> & M;
  }): IDataSource<T, P> & M {
    return useMock ? new mockDataSource() : new apiDataSource();
  }
}

/**
 * Mock状态标记
 * 用于调试和开发环境识别
 */
export const __MOCK__ = useMock;

/**
 * 当前数据源类型
 */
export const __DATA_SOURCE_TYPE__ = useMock ? 'mock' : 'api';