import { Injectable, Logger } from "@nestjs/common"
import * as admin from "firebase-admin"
import { initializeFirebase } from "src/config/firebase.config"

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

  constructor() {
    initializeFirebase()
  }

  /**
   * Send push notification to a single device
   */
  async sendToDevice(
    token: string,
    title: string,
    body: string,
    data: Record<string, string> = {},
  ) {
    try {
      const message: admin.messaging.Message = {
        token,
        notification: { title, body },
        data,
      }

      const response = await admin.messaging().send(message)
      this.logger.log(`Notification sent successfully: ${response}`)
      return response
    } catch (error) {
      this.logger.error("Error sending notification:", error)
      return
    }
  }

  /**
   * Send notification to multiple devices
   */
  // async sendToMultipleDevices(
  //   tokens: string[],
  //   title: string,
  //   body: string,
  //   data: Record<string, string> = {},
  // ) {
  //   try {
  //     const iconUrl = process.env.FIREBASE_NOTIFICATION_ICON

  //     const safeData = Object.fromEntries(
  //       Object.entries(data).map(([k, v]) => [k, String(v)]),
  //     )

  //     const message: admin.messaging.MulticastMessage = {
  //       tokens,
  //       notification: { title, body, ...(iconUrl ? { icon: iconUrl } : {}) },
  //       data: safeData,
  //     }

  //     const response = await admin.messaging().sendEachForMulticast(message)

  //     this.logger.log(
  //       `Notifications sent: success=${response.successCount}, failure=${response.failureCount}`,
  //     )

  //     const failedTokens: string[] = []
  //     if (response.failureCount > 0) {
  //       response.responses.forEach((resp, idx) => {
  //         if (!resp.success) {
  //           this.logger.warn(`Failed to send to ${tokens[idx]}: ${resp.error}`)
  //           // Check for specific error codes indicating invalid or expired tokens
  //           if (
  //             resp.error?.code === "messaging/invalid-argument" ||
  //             resp.error?.code === "messaging/registration-token-not-registered"
  //           ) {
  //             failedTokens.push(tokens[idx])
  //           }
  //         }
  //       })
  //     }

  //     return { response, failedTokens }
  //   } catch (error) {
  //     this.logger.error("Error sending multicast notification:", error)
  //     return
  //   }
  // }

  async sendToMultipleDevices(
    tokens: string[],
    title: string,
    body: string,
    data: Record<string, any> = {},
  ) {
    try {
      const iconUrl = process.env.FIREBASE_NOTIFICATION_ICON

      // ✅ Properly handle nested objects
      const safeData = Object.fromEntries(
        Object.entries(data).map(([k, v]) => [
          k,
          typeof v === "object" && v !== null ? JSON.stringify(v) : String(v),
        ]),
      )

      const message: admin.messaging.MulticastMessage = {
        tokens,
        notification: { title, body, ...(iconUrl ? { icon: iconUrl } : {}) },
        data: safeData,
      }

      const response = await admin.messaging().sendEachForMulticast(message)

      this.logger.log(
        `Notifications sent: success=${response.successCount}, failure=${response.failureCount}`,
      )

      const failedTokens: string[] = []
      if (response.failureCount > 0) {
        response.responses.forEach((resp, idx) => {
          if (!resp.success) {
            this.logger.warn(`Failed to send to ${tokens[idx]}: ${resp.error}`)
            // Check for specific error codes indicating invalid or expired tokens
            if (
              resp.error?.code === "messaging/invalid-argument" ||
              resp.error?.code === "messaging/registration-token-not-registered"
            ) {
              failedTokens.push(tokens[idx])
            }
          }
        })
      }

      return { response, failedTokens }
    } catch (error) {
      this.logger.error("Error sending multicast notification:", error)
      return
    }
  }
}
