import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import axios from 'axios';
import * as admin from 'firebase-admin';

@Injectable()
/**
 * NotificationService: مركز التنبيهات
 * المسؤول عن إرسال الرسائل إلى Telegram, Slack, و FCM (تنبيهات الهاتف)
 */
export class NotificationService {
  private readonly logger = new Logger(NotificationService.name);

  /**
   * نستخدم الـ constructor هنا لحقن ConfigService
   * وأيضاً لتهيئة Firebase Admin بمجرد تشغيل الخدمة
   */
  constructor(private readonly configService: ConfigService) {
    this.initializeFirebase();
  }

  private initializeFirebase() {
    const serviceAccount = this.configService.get<string>('notifications.firebase.serviceAccount');
    if (serviceAccount && admin.apps.length === 0) {
      try {
        const cert = typeof serviceAccount === 'string' && serviceAccount.trim().startsWith('{')
          ? JSON.parse(serviceAccount)
          : serviceAccount; // Path or JSON string

        admin.initializeApp({
          credential: admin.credential.cert(cert),
        });
        this.logger.log('Firebase Admin initialized successfully | تم تهيئة فيربيز بنجاح');
      } catch (error) {
        this.logger.error(`Failed to initialize Firebase: ${error.message}`);
      }
    }
  }

  /**
   * Send notification to multiple channels
   * إرسال تنبيه عبرة قنوات متعددة
   */
  async send(
    message: string,
    channels: ('telegram' | 'slack' | 'fcm')[],
    options?: { fcmToken?: string },
  ): Promise<void> {
    this.logger.log(`Sending notification: ${message} to ${channels.join(', ')}`);

    const promises = channels.map((channel) => {
      switch (channel) {
        case 'telegram':
          return this.sendTelegram(message);
        case 'slack':
          return this.sendSlack(message);
        case 'fcm':
          return options?.fcmToken
            ? this.sendFcm(options.fcmToken, 'SaaS Pro Alert | تنبيه برو', message)
            : Promise.resolve();
        default:
          return Promise.resolve();
      }
    });

    await Promise.allSettled(promises);
  }

  /**
   * Send Telegram message
   * إرسال رسالة تيليجرام
   */
  private async sendTelegram(message: string): Promise<void> {
    const botToken = this.configService.get<string>('notifications.telegramToken');
    const chatId = this.configService.get<string>('notifications.telegramChatId');

    if (!botToken || !chatId) {
      this.logger.warn('Telegram notifications not configured.');
      return;
    }

    const url = `https://api.telegram.org/bot${botToken}/sendMessage`;
    try {
      await axios.post(url, {
        chat_id: chatId,
        text: `🔔 *SaaS Pro Alert*\n\n${message}`,
        parse_mode: 'Markdown',
      });
    } catch (error) {
      this.logger.error(`Telegram Error: ${error.message}`);
    }
  }

  /**
   * Send Slack message
   * إرسال رسالة سلاك
   */
  private async sendSlack(message: string): Promise<void> {
    const webhookUrl = this.configService.get<string>('notifications.slackWebhookUrl');

    if (!webhookUrl) {
      this.logger.warn('Slack notifications not configured.');
      return;
    }

    try {
      await axios.post(webhookUrl, {
        text: `🚀 *SaaS Pro Notification*\n${message}`,
      });
    } catch (error) {
      this.logger.error(`Slack Error: ${error.message}`);
    }
  }

  /**
   * Send Firebase Cloud Message (FCM)
   * إرسال تنبيه عبر فيربيز
   */
  async sendFcm(token: string, title: string, body: string): Promise<void> {
    if (admin.apps.length === 0) {
      this.logger.warn('FCM not configured (No Firebase app initialized).');
      return;
    }
    try {
      await admin.messaging().send({
        token,
        notification: {
          title,
          body,
        },
        data: {
          click_action: 'FLUTTER_NOTIFICATION_CLICK',
        },
      });
      this.logger.log(`FCM sent to token ending in: ...${token.substring(token.length - 5)}`);
    } catch (error) {
      this.logger.error(`FCM Error: ${error.message}`);
    }
  }
}
