/**
 * MiniProgram Streaming Adapter
 *
 * 基于 WebSocket 的流式请求适配器实现（小程序不支持 SSE）
 */

import type { IStreamingAdapter, StreamConfig } from './interface';

export class MiniprogramStreamingAdapter implements IStreamingAdapter {
  private Taro: any;
  private socketTask: any = null;
  private connected: boolean = false;

  constructor(Taro: any) {
    this.Taro = Taro;
  }

  async connect(config: StreamConfig): Promise<void> {
    return new Promise((resolve, reject) => {
      // 将 HTTP URL 转换为 WebSocket URL
      const wsUrl = config.url.replace(/^http/, 'ws');

      this.socketTask = this.Taro.connectSocket({
        url: wsUrl,
        header: config.headers || {},
        success: () => {
          this.connected = true;
          resolve();
        },
        fail: (error: any) => {
          config.onError?.(error);
          reject(error);
        },
      });

      this.socketTask.onOpen(() => {
        this.connected = true;
        // 发送初始数据
        if (config.data) {
          this.socketTask.send({
            data: JSON.stringify(config.data),
          });
        }
      });

      this.socketTask.onMessage((res: any) => {
        try {
          const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
          config.onMessage(data);
        } catch (error) {
          console.error('Failed to parse WebSocket message:', error);
        }
      });

      this.socketTask.onError((error: any) => {
        this.connected = false;
        config.onError?.(error);
      });

      this.socketTask.onClose(() => {
        this.connected = false;
        config.onComplete?.();
      });
    });
  }

  disconnect(): void {
    if (this.socketTask) {
      this.socketTask.close();
      this.socketTask = null;
    }
    this.connected = false;
  }

  isConnected(): boolean {
    return this.connected;
  }
}
