import { ILogData } from './types';

const LOG_STREAM_URL = '/api/v1/workflow/instance/log';

export class LogStreamService {
  private eventSource: EventSource | null = null;

  connect(processInstanceId: string, onMessage: (log: ILogData) => void, onError?: (error: any) => void) {
    if (this.eventSource) {
      this.disconnect();
    }

    const token = localStorage.getItem('token');
    const url = new URL(`${window.location.origin}${LOG_STREAM_URL}/dfcd8ee0-bc79-11ef-96b6-2ecf01f9c5d5`);
    
    if (token) {
      url.searchParams.append('token', token);
    }

    this.eventSource = new EventSource(url.toString());

    this.eventSource.addEventListener('STDOUT', (event) => {
      onMessage({
        type: 'STDOUT',
        data: event.data,
        timestamp: new Date().toISOString()
      });
    });

    this.eventSource.addEventListener('STDERR', (event) => {
      onMessage({
        type: 'STDERR',
        data: event.data,
        timestamp: new Date().toISOString()
      });
    });

    this.eventSource.onerror = (error) => {
      if (onError) {
        onError(error);
      }
      this.disconnect();
    };
  }

  disconnect() {
    if (this.eventSource) {
      this.eventSource.close();
      this.eventSource = null;
    }
  }
}

export const logStreamService = new LogStreamService(); 