import { Injectable, Logger } from '@nestjs/common';
import { WhatsappWebService } from './services/whatsapp-web.service';
import { WhatsappButton } from 'src/modules/whatsapp/interfaces/whatsapp-messaging.interface';
import { IWhatsappOutboundService } from 'src/modules/whatsapp-019/interfaces/whatsapp-outbound.interface';

@Injectable()
export class WhatsappWebMessagingService implements IWhatsappOutboundService {
  private readonly logger = new Logger(WhatsappWebMessagingService.name);

  constructor(private readonly whatsappWebService: WhatsappWebService) {}

  async sendTyping(to: string, timeoutMs: number = 60000): Promise<unknown> {
    return this.whatsappWebService.sendTyping(to, timeoutMs);
  }

  async sendTextMessage(to: string, text: string): Promise<unknown> {
    this.logger.log(
      `WhatsappWebMessagingService.sendTextMessage: Sending text message to ${to}`,
    );
    return this.whatsappWebService.sendText(to, text);
  }

  async sendImageMessage(
    to: string,
    imageUrl: string,
    caption: string,
  ): Promise<unknown> {
    this.logger.log(
      `WhatsappWebMessagingService.sendImageMessage: Sending image message to ${to}, imageUrl=${imageUrl}`,
    );
    return this.whatsappWebService.sendImage(to, imageUrl, caption);
  }

  async sendButtonsMessage(
    to: string,
    text: string,
    buttons: WhatsappButton[],
  ): Promise<unknown> {
    this.logger.log(
      `WhatsappWebMessagingService.sendButtonsMessage: Wizzo API does not support interactive buttons - falling back to text for ${to}, buttonsCount=${buttons.length}`,
    );
    const buttonLabels = buttons.map((b) => b.title).join(' | ');
    const fallbackText = text + (buttonLabels ? `\n\n${buttonLabels}` : '');
    return this.whatsappWebService.sendText(to, fallbackText);
  }
}
