/**
 * HTTP客户端使用示例
 */

import { HttpClient, RequestInterceptor, ResponseInterceptor } from './http';
import { Storage } from '../utils/storage';

// 基础使用示例
export function basicUsageExample() {
  // 创建HTTP客户端实例
  const httpClient = new HttpClient({
    baseURL: 'https://api.example.com',
    timeout: 10000,
    withCredentials: true
  });

  // 设置Token获取函数
  httpClient.setTokenGetter(() => {
    // 从TokenManager或其他地方获取Token
    return localStorage.getItem('auth_token') || '';
  });

  // 设置租户ID
  httpClient.setTenantId('tenant-123');

  return httpClient;
}

// 拦截器使用示例
export function interceptorExample() {
  const httpClient = new HttpClient();

  // 请求拦截器 - 添加通用头信息
  const authInterceptor: RequestInterceptor = {
    onRequest: (options) => {
      // 添加认证头
      const token = localStorage.getItem('auth_token');
      if (token) {
        options.headers = {
          ...options.headers,
          'Authorization': `Bearer ${token}`
        };
      }
      
      // 添加请求ID用于追踪
      options.headers = {
        ...options.headers,
        'X-Request-ID': Math.random().toString(36).substr(2, 9)
      };
      
      return options;
    },
    onRequestError: (error) => {
      console.error('请求拦截器错误:', error);
      return Promise.reject(error);
    }
  };

  // 响应拦截器 - 统一处理响应格式
  const responseInterceptor: ResponseInterceptor = {
    onResponse: (response) => {
      // 记录响应时间
      console.log(`Response received: ${response.status} ${response.statusText}`);
      
      // 可以在这里统一处理某些业务逻辑
      return response;
    },
    onResponseError: (error) => {
      // 统一错误处理
      if (error.status === 401) {
        // Token过期，跳转到登录页
        window.location.href = '/login';
      }
      
      console.error('Response error:', error.message);
      return Promise.reject(error);
    }
  };

  // 添加拦截器
  httpClient.addRequestInterceptor(authInterceptor);
  httpClient.addResponseInterceptor(responseInterceptor);

  return httpClient;
}

// 工厂方法使用示例
export function factoryMethodExample() {
  // 创建不同环境的客户端实例
  const devClient = HttpClient.create('https://dev-api.example.com', {
    timeout: 5000,
    withCredentials: true
  });

  const prodClient = HttpClient.create('https://api.example.com', {
    timeout: 15000,
    withCredentials: true
  });

  return { devClient, prodClient };
}

// 配置管理示例
export function configManagementExample() {
  const httpClient = new HttpClient({
    baseURL: 'https://api.example.com'
  });

  // 获取当前配置
  const currentConfig = httpClient.getConfig();
  console.log('Current config:', currentConfig);

  // 动态更新配置
  httpClient.updateConfig({
    timeout: 20000,
    headers: {
      'X-API-Version': 'v2'
    }
  });

  // 验证配置更新
  const updatedConfig = httpClient.getConfig();
  console.log('Updated config:', updatedConfig);

  return httpClient;
}

// 实际API调用示例
export async function apiCallExample() {
  const httpClient = basicUsageExample();

  try {
    // GET请求
    const getUsers = await httpClient.get('/users', {
      needAuth: true,
      timeout: 8000
    });
    console.log('Users:', getUsers.data);

    // POST请求
    const createUser = await httpClient.post('/users', {
      name: 'John Doe',
      email: 'john@example.com'
    }, {
      needAuth: true
    });
    console.log('Created user:', createUser.data);

    // PUT请求
    const updateUser = await httpClient.put('/users/1', {
      name: 'Jane Doe'
    });
    console.log('Updated user:', updateUser.data);

    // DELETE请求
    const deleteUser = await httpClient.delete('/users/1');
    console.log('Delete result:', deleteUser.data);

  } catch (error) {
    if (error instanceof Error) {
      console.error('API call failed:', error.message);
    }
  }
}

// 错误处理示例
export function errorHandlingExample() {
  // 不同类型的错误处理
  const handleHttpError = (error: any) => {
    if (error instanceof Error) {
      if ('status' in error) {
        // HTTP错误
        const httpError = error as any;
        switch (httpError.status) {
          case 401:
            console.log('未授权，请重新登录');
            break;
          case 403:
            console.log('禁止访问');
            break;
          case 404:
            console.log('资源不存在');
            break;
          case 500:
            console.log('服务器内部错误');
            break;
          default:
            console.log(`HTTP错误: ${httpError.status} - ${httpError.message}`);
        }
      } else {
        // 网络错误或其他错误
        console.log('网络错误:', error.message);
      }
    }
  };

  return handleHttpError;
}

// 完整的实际应用示例
export class ApiService {
  private httpClient: HttpClient;

  constructor() {
    this.httpClient = new HttpClient({
      baseURL: process.env.API_BASE_URL || 'https://api.example.com',
      timeout: 15000
    });

    // 设置全局拦截器
    this.setupInterceptors();
  }

  private setupInterceptors() {
    // 请求拦截器
    this.httpClient.addRequestInterceptor({
      onRequest: (options) => {
        // 添加时间戳防止缓存
        if (options.method === 'GET') {
          const separator = options.url.includes('?') ? '&' : '?';
          options.url += `${separator}_t=${Date.now()}`;
        }
        return options;
      }
    });

    // 响应拦截器
    this.httpClient.addResponseInterceptor({
      onResponse: (response) => {
        // 统一日志记录
        console.log(`[${response.status}] ${response.statusText}`);
        return response;
      },
      onResponseError: (error) => {
        // 统一错误上报
        console.error('API Error:', {
          status: error.status,
          message: error.message,
          url: window.location.href
        });
        return Promise.reject(error);
      }
    });
  }

  // 用户相关API
  async getUsers(page: number = 1, size: number = 10) {
    const queryParams = new URLSearchParams({
      page: page.toString(),
      size: size.toString()
    });
    return this.httpClient.get(`/users?${queryParams}`);
  }

  async getUserById(id: string) {
    return this.httpClient.get(`/users/${id}`);
  }

  async createUser(userData: any) {
    return this.httpClient.post('/users', userData);
  }

  async updateUser(id: string, userData: any) {
    return this.httpClient.put(`/users/${id}`, userData);
  }

  async deleteUser(id: string) {
    return this.httpClient.delete(`/users/${id}`);
  }

  // 认证相关API
  async login(credentials: { username: string; password: string }) {
    return this.httpClient.post('/auth/login', credentials, {
      needAuth: false
    });
  }

  async refreshToken(refreshToken: string) {
    return this.httpClient.post('/auth/refresh', { refreshToken }, {
      needAuth: false
    });
  }

  async logout() {
    return this.httpClient.post('/auth/logout');
  }
}