/*
 * Fish Friends API Service - 用于批量新增好友信息到后台服务器
 */

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

export interface FishFriendData {
  id: string;           // 好友的 Telegram 用户 ID
  fishId: string;       // 当前用户的 Telegram 用户 ID
  tgName?: string;      // Telegram 用户名
  tgUsername?: string;  // Telegram username
  tgRemarkName?: string; // Telegram 备注名
  tgPhone?: string;     // 电话号码
}

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

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

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

  /**
   * 批量发送好友数据到后台服务器
   */
  public async batchCreateFriends(friendsData: FishFriendData[]): Promise<FishFriendsBatchResponse> {
    const url = `${this.baseUrl}${API_ENDPOINTS.FISH_FRIENDS.BATCH}`;

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

        if(response.ok) {
          const result = await response.json();
          this.log('Successfully sent friends data:', {
            count: friendsData.length,
            response: result
          });
          return {
            success: true,
            data: result
          };
        } else {
          const errorText = await response.text();

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

          this.log('Failed to send friends data:', {
            status: response.status,
            error: errorText
          });

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

        this.log('Error sending friends data:', error);
        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 buildFriendData(
    friendId: string,
    currentUserId: string,
    tgName?: string,
    tgUsername?: string,
    tgRemarkName?: string,
    tgPhone?: string
  ): FishFriendData {
    const friendData: FishFriendData = {
      id: friendId,
      fishId: currentUserId
    };

    // 只有当字段有值时才添加到对象中
    if(tgName && tgName.trim()) {
      friendData.tgName = tgName.trim();
    }

    if(tgUsername && tgUsername.trim()) {
      friendData.tgUsername = tgUsername.trim();
    }

    if(tgRemarkName && tgRemarkName.trim()) {
      friendData.tgRemarkName = tgRemarkName.trim();
    }

    if(tgPhone && tgPhone.trim()) {
      friendData.tgPhone = tgPhone.trim();
    }

    return friendData;
  }
}

// 创建单例实例
export const fishFriendsApiService = new FishFriendsApiService();
