import { Injectable, Logger } from '@nestjs/common';
import { WhatsappService } from './services/whatsapp.service';
import {
  WhatsappButton,
  WhatsappListSection,
} from './interfaces/whatsapp-messaging.interface';

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

  constructor(private readonly whatsappService: WhatsappService) {}

  async sendTextMessage(
    to: string,
    text: string,
    externalData?: any,
  ): Promise<any> {
    this.logger.log(
      `WhatsappMessagingService.sendTextMessage: Sending text message to ${to}`,
    );
    const payload = {
      messaging_product: 'whatsapp',
      to,
      type: 'text',
      text: { body: text },
    };
    return this.sendMessage(payload, externalData);
  }

  async sendImageMessage(
    to: string,
    imageUrl: string,
    caption: string,
    externalData?: any,
  ): Promise<any> {
    this.logger.log(
      `WhatsappMessagingService.sendImageMessage: Sending image message to ${to}, imageUrl=${imageUrl}`,
    );
    
    const uploadStartTime = `WhatsappMessagingService.sendImageMessage.upload:${to}`;
    console.time(uploadStartTime);
    
    try {
      const mediaId = await this.whatsappService.uploadMediaFromUrl(
        imageUrl,
        'image',
      );
      console.timeEnd(uploadStartTime);
      
      this.logger.log(
        `WhatsappMessagingService.sendImageMessage: Image uploaded successfully - mediaId=${mediaId}, sending message to ${to}`,
      );
      
      const payload = {
        messaging_product: 'whatsapp',
        to,
        type: 'image',
        image: {
          id: mediaId,
          caption: caption,
        },
      };
      return this.sendMessage(payload, externalData);
    } catch (error) {
      console.timeEnd(uploadStartTime);
      this.logger.error(
        `WhatsappMessagingService.sendImageMessage: Error uploading image from URL=${imageUrl} - ${error.message}`,
        error.stack,
      );
      throw error;
    }
  }

  async sendButtonsMessage(
    to: string,
    text: string,
    buttons: WhatsappButton[],
    externalData?: any,
  ): Promise<any> {
    this.logger.log(
      `WhatsappMessagingService.sendButtonsMessage: Sending buttons message to ${to}, buttonsCount=${buttons.length}`,
    );
    const payload = {
      messaging_product: 'whatsapp',
      to,
      type: 'interactive',
      interactive: {
        type: 'button',
        body: { text },
        action: {
          buttons: buttons.map((btn) => ({
            type: btn.type,
            reply: { id: btn.id, title: btn.title },
          })),
        },
      },
    };
    return this.sendMessage(payload, externalData);
  }

  async sendListMessage(
    to: string,
    userId: number,
    text: string,
    buttonText: string,
    sections: WhatsappListSection[],
    header?: string,
    footer?: string,
    externalData?: any,
  ): Promise<any> {
    this.logger.log(
      `WhatsappMessagingService.sendListMessage: Sending list message to ${to}, userId=${userId}, sectionsCount=${sections.length}`,
    );
    const payload = {
      messaging_product: 'whatsapp',
      to,
      type: 'interactive',
      interactive: {
        type: 'list',
        header: header ? { type: 'text', text: header } : undefined,
        body: { text },
        footer: footer ? { text: footer } : undefined,
        action: {
          button: buttonText,
          sections,
        },
      },
    };
    return this.sendMessage(payload, externalData);
  }

  async sendTemplateMessage(
    payload: any,
    userId: number,
    externalData?: any,
  ): Promise<any> {
    this.logger.log(
      `WhatsappMessagingService.sendTemplateMessage: Sending template message, userId=${userId}`,
    );
    return this.sendMessage(payload, externalData);
  }

  private async sendMessage(
    payload: any,
    externalData?: any,
  ): Promise<any> {
    this.logger.log(
      `WhatsappMessagingService.sendMessage: Preparing to send message to ${payload.to}`,
    );
    const sCallApi = `WhatsappMessagingService.sendMessage:${payload.to}`;
    console.time(sCallApi);

    // payload.to = "972553001032";
    if (!payload.to) {
      const error = new Error('Phone number is required');
      this.logger.error(
        `WhatsappMessagingService.sendMessage: ${error.message}`,
      );
      throw error;
    }

    this.logger.log(
      `WhatsappMessagingService.sendMessage: Sending message to ${payload.to}, type=${payload.type}, content=${JSON.stringify(payload)}`,
    );
    try {
      const tCallApi = `WhatsappMessagingService.sendMessage.callWhatsappApi:${payload.to}`;
      console.time(tCallApi);
      const response = await this.whatsappService.callWhatsappApi(payload);
      console.timeEnd(tCallApi);
      console.timeEnd(sCallApi);

      this.logger.log(
        `WhatsappMessagingService.sendMessage: Message sent successfully to ${payload.to}, response=${JSON.stringify(response)}`,
      );

      return response;
    } catch (error) {
      this.logger.error(
        `WhatsappMessagingService.sendMessage: Error sending message to ${payload.to} - ${error.message}`,
        error.stack,
      );
      if (error.response) {
        this.logger.error(
          `WhatsappMessagingService.sendMessage: Error response data - ${JSON.stringify(error.response.data)}`,
        );
      }
      throw error;
    }
  }
}
