import { Injectable } from '@nestjs/common';
import {
  ChannelAdapterPort,
  SendMessageParams,
  DeliveryResult,
} from '../../domain/ports/outbound/channel-adapter.port';
import { ChannelType } from '../../domain/value-objects/channel-type.vo';
import { RealtimeGateway } from '../../interfaces/ws/realtime.gateway';
import { randomUUID } from 'crypto';

@Injectable()
export class WebSocketAdapter implements ChannelAdapterPort {
  readonly channelType = ChannelType.PUSH;

  constructor(private readonly gateway: RealtimeGateway) {}

  async send(params: SendMessageParams): Promise<DeliveryResult> {
    try {
      this.gateway.broadcastNotification(params.to.tenantId, {
        type: 'message',
        content: params.content,
        priority: params.priority,
        contactId: params.to.id,
        sentAt: new Date().toISOString(),
      });

      return { messageId: randomUUID(), status: 'sent' };
    } catch (error) {
      return {
        messageId: randomUUID(),
        status: 'failed',
        error: error instanceof Error ? error.message : 'WebSocket send failed',
      };
    }
  }

  async isAvailable(): Promise<boolean> {
    return true;
  }
}
