/**
 * 推送服务 - 管理设备Token和推送记录
 */

import { api } from './api';
import { 
  DeviceTokenResponse, 
  RegisterDeviceRequest, 
  PushRecordResponse 
} from '../types/dto';

// 推送服务类
class PushService {
  /**
   * 注册设备
   * POST /api/v1/push/devices
   * @param data 设备注册信息
   */
  async registerDevice(data: RegisterDeviceRequest): Promise<DeviceTokenResponse> {
    const response = await api.post<DeviceTokenResponse>('/push/devices', data);
    return response.data;
  }

  /**
   * 获取当前用户的所有设备列表
   * GET /api/v1/push/devices
   */
  async getDevices(): Promise<DeviceTokenResponse[]> {
    try {
      const response = await api.get<DeviceTokenResponse[]>('/push/devices');
      return response.data;
    } catch (error) {
      console.error('获取设备列表失败:', error);
      return [];
    }
  }

  /**
   * 注销设备（删除设备Token）
   * DELETE /api/v1/push/devices/:deviceId
   * @param deviceId 设备ID
   */
  async unregisterDevice(deviceId: string): Promise<void> {
    await api.delete(`/push/devices/${deviceId}`);
  }

  /**
   * 更新设备推送Token
   * PUT /api/v1/push/devices/:deviceId/token
   * @param deviceId 设备ID
   * @param pushToken 新的推送Token
   */
  async updateDeviceToken(deviceId: string, pushToken: string): Promise<void> {
    await api.put(`/push/devices/${deviceId}/token`, { push_token: pushToken });
  }

  /**
   * 获取推送记录
   * GET /api/v1/push/records
   * @param limit 返回数量限制
   * @param offset 偏移量
   */
  async getPushRecords(limit?: number, offset?: number): Promise<PushRecordResponse[]> {
    const params: Record<string, any> = {};
    if (limit !== undefined) {
      params.limit = limit;
    }
    if (offset !== undefined) {
      params.offset = offset;
    }

    try {
      const response = await api.get<PushRecordResponse[]>('/push/records', params);
      return response.data;
    } catch (error) {
      console.error('获取推送记录失败:', error);
      return [];
    }
  }

  /**
   * 设置设备活跃状态
   * PUT /api/v1/push/devices/:deviceId/active
   * @param deviceId 设备ID
   * @param isActive 是否活跃
   */
  async setDeviceActive(deviceId: string, isActive: boolean): Promise<void> {
    await api.put(`/push/devices/${deviceId}/active`, { is_active: isActive });
  }
}

// 导出推送服务实例
export const pushService = new PushService();

// 导出便捷方法（与任务要求保持一致）
export const registerDevice = (data: RegisterDeviceRequest): Promise<DeviceTokenResponse> => 
  pushService.registerDevice(data);

export const getDevices = (): Promise<DeviceTokenResponse[]> => 
  pushService.getDevices();

export const unregisterDevice = (deviceId: string): Promise<void> => 
  pushService.unregisterDevice(deviceId);

export const updateDeviceToken = (deviceId: string, pushToken: string): Promise<void> => 
  pushService.updateDeviceToken(deviceId, pushToken);

export const getPushRecords = (limit?: number, offset?: number): Promise<PushRecordResponse[]> => 
  pushService.getPushRecords(limit, offset);

export default pushService;
