// 好友功能API客户端
const apiClient = require('./api-client.js');

class FriendAPI {
  constructor() {
    this.apiClient = apiClient;
  }

  // 🔥 ===== 好友管理 =====

  // 添加好友
  async addFriend(targetId, message = '') {
    try {
      const response = await this.apiClient.post('/api/v1/social/friend/add', {
        targetId: targetId,
        message: message
      });
      return response;
    } catch (error) {
      console.error('添加好友失败:', error);
      throw error;
    }
  }

  // 获取好友列表
  async getFriendList() {
    try {
      const response = await this.apiClient.get('/api/v1/social/friends');
      return response;
    } catch (error) {
      console.error('获取好友列表失败:', error);
      throw error;
    }
  }

  // 获取好友详情
  async getFriendDetail(customId, lat = null, lng = null) {
    try {
      const params = {};
      if (lat !== null && lng !== null) {
        params.lat = lat;
        params.lng = lng;
      }
      
      const response = await this.apiClient.get(`/api/v1/social/friends/${customId}/detail`, params);
      return response;
    } catch (error) {
      console.error('获取好友详情失败:', error);
      throw error;
    }
  }

  // 删除好友
  async deleteFriend(customId) {
    try {
      const response = await this.apiClient.delete(`/api/v1/social/friend/${customId}`);
      return response;
    } catch (error) {
      console.error('删除好友失败:', error);
      throw error;
    }
  }

  // 更新好友关系
  async updateFriendRelation(friendId, updates) {
    try {
      const response = await this.apiClient.put('/api/v1/social/friend', {
        friendId: friendId,
        ...updates
      });
      return response;
    } catch (error) {
      console.error('更新好友关系失败:', error);
      throw error;
    }
  }

  // 删除好友
  async deleteFriend(friendId) {
    try {
      const response = await this.apiClient.delete(`/api/v1/social/friend/${friendId}`);
      return response;
    } catch (error) {
      console.error('删除好友失败:', error);
      throw error;
    }
  }

  // 🔥 ===== 好友请求管理 =====

  // 获取好友请求列表
  async getFriendRequests() {
    try {
      const response = await this.apiClient.get('/api/v1/social/friend/requests');
      return response;
    } catch (error) {
      console.error('获取好友请求列表失败:', error);
      throw error;
    }
  }

  // 获取待处理好友请求数量
  async getFriendRequestCount() {
    try {
      const response = await this.apiClient.get('/api/v1/social/friend/requests/count');
      return response;
    } catch (error) {
      console.error('获取好友请求数量失败:', error);
      throw error;
    }
  }

  // 处理好友请求
  async handleFriendRequest(requestId, accept) {
    try {
      const response = await this.apiClient.post('/api/v1/social/friend/handle-request', {
        requestId: requestId,
        accept: accept
      });
      return response;
    } catch (error) {
      console.error('处理好友请求失败:', error);
      throw error;
    }
  }

  // 批量处理好友请求
  async batchHandleFriendRequests(requestIds, accept) {
    try {
      const response = await this.apiClient.post('/api/v1/social/friend/batch-handle-requests', {
        requestIds: requestIds,
        accept: accept
      });
      return response;
    } catch (error) {
      console.error('批量处理好友请求失败:', error);
      throw error;
    }
  }

  // 🔥 ===== 用户搜索 =====

  // 搜索用户 - 根据正确的接口文档
  async searchUsers(query, searchType = 'all', page = 1, pageSize = 10) {
    try {
      const response = await this.apiClient.post('/api/v1/social/users/search', {
        query: query,
        searchType: searchType,
        page: page,
        pageSize: pageSize
      });
      return response;
    } catch (error) {
      console.error('搜索用户失败:', error);
      throw error;
    }
  }

  // 🔥 ===== 通知管理（轮询降级） =====

  // 拉取好友通知
  async pullFriendNotifications(limit = 10) {
    try {
      const response = await this.apiClient.get('/api/v1/social/friend/notifications/pull', {
        limit: limit
      });
      return response;
    } catch (error) {
      console.error('拉取好友通知失败:', error);
      throw error;
    }
  }

  // 获取通知统计
  async getNotificationStats() {
    try {
      const response = await this.apiClient.get('/api/v1/social/friend/notifications/stats');
      return response;
    } catch (error) {
      console.error('获取通知统计失败:', error);
      throw error;
    }
  }

  // 清除通知缓存
  async clearNotificationCache() {
    try {
      const response = await this.apiClient.delete('/api/v1/social/friend/notifications/clear');
      return response;
    } catch (error) {
      console.error('清除通知缓存失败:', error);
      throw error;
    }
  }

  // 🔥 ===== 工具方法 =====

  // 格式化关系状态文本
  getRelationStatusText(relationStatus) {
    const statusMap = {
      'self': '自己',
      'friend': '已是好友',
      'can_add': '可以添加好友',
      'pending': '等待验证',
      'privacy_limited': '隐私限制',
      'blocked': '被拉黑'
    };
    return statusMap[relationStatus] || '未知状态';
  }

  // 格式化搜索类型文本
  getSearchTypeText(searchType) {
    const typeMap = {
      'nickname': '昵称',
      'custom_id': '用户ID',
      'phone': '手机号',
      'all': '全部'
    };
    return typeMap[searchType] || '未知类型';
  }

  // 格式化隐私级别文本
  getPrivacyLevelText(privacyLevel) {
    const levelMap = {
      1: '精确位置',
      2: '区县级别',
      3: '城市级别',
      4: '不可见'
    };
    return levelMap[privacyLevel] || '未知级别';
  }

  // 格式化关系标签
  getRelationLabelText(relation) {
    const relationMap = {
      '情侣': '💕 情侣',
      '家人': '👨‍👩‍👧‍👦 家人',
      '兄弟': '👬 兄弟',
      '姐妹': '👭 姐妹',
      '闺蜜': '👯‍♀️ 闺蜜',
      '死党': '🤝 死党'
    };
    return relationMap[relation] || relation;
  }

  // 计算友谊天数
  calculateFriendshipDays(friendshipDate) {
    if (!friendshipDate) return 0;
    
    const now = new Date();
    const friendDate = new Date(friendshipDate);
    const diffTime = Math.abs(now - friendDate);
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    return diffDays;
  }

  // 格式化友谊时间描述
  formatFriendshipTime(friendshipDate) {
    if (!friendshipDate) return '未知时间';
    
    const days = this.calculateFriendshipDays(friendshipDate);
    
    if (days < 1) {
      return '今天成为好友';
    } else if (days < 30) {
      return `${days}天前成为好友`;
    } else if (days < 365) {
      const months = Math.floor(days / 30);
      return `${months}个月前成为好友`;
    } else {
      const years = Math.floor(days / 365);
      return `${years}年前成为好友`;
    }
  }

  // 验证CustomID格式
  validateCustomId(customId) {
    if (!customId || typeof customId !== 'string') {
      return false;
    }
    
    // CustomID应该是9-10位数字字符串
    const customIdRegex = /^\d{9,10}$/;
    return customIdRegex.test(customId);
  }

  // 脱敏手机号
  maskPhoneNumber(phone) {
    if (!phone || phone.length < 11) {
      return phone;
    }
    
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
  }

  // 生成好友分组列表
  getFriendGroups() {
    return [
      '默认分组',
      '家人',
      '同学',
      '同事',
      '朋友',
      '其他'
    ];
  }

  // 生成关系标签列表
  getRelationLabels() {
    return [
      { value: '情侣', label: '💕 情侣', color: '#ff4757' },
      { value: '家人', label: '👨‍👩‍👧‍👦 家人', color: '#2ed573' },
      { value: '兄弟', label: '👬 兄弟', color: '#3742fa' },
      { value: '姐妹', label: '👭 姐妹', color: '#ff6b81' },
      { value: '闺蜜', label: '👯‍♀️ 闺蜜', color: '#a55eea' },
      { value: '死党', label: '🤝 死党', color: '#26de81' }
    ];
  }
}

// 创建全局单例
const friendAPI = new FriendAPI();

module.exports = friendAPI;
