import { Injectable, Logger } from '@nestjs/common';
import { Notification, NotificationChannel } from '../../domain/entities/notification.entity';
import { INotificationProvider } from '../../domain/ports/notification-provider.interface';
import { PushDispatcherService } from '../../application/services/push-dispatcher.service';

/**
 * Push notification provider — bridges the per-user Notification system
 * to the multi-channel device push dispatcher (FCM/APNs/HMS/Xiaomi/OPPO/vivo).
 *
 * Implements INotificationProvider so NotificationService channel dispatch remains unchanged.
 */
@Injectable()
export class PushNotificationProvider implements INotificationProvider {
  private readonly logger = new Logger(PushNotificationProvider.name);
  readonly channel = NotificationChannel.PUSH;

  constructor(private readonly pushDispatcher: PushDispatcherService) {}

  async send(notification: Notification): Promise<boolean> {
    try {
      await this.pushDispatcher.sendToUser(
        notification.userId,
        notification.title,
        notification.body,
        notification.data
          ? Object.fromEntries(
              Object.entries(notification.data).map(([k, v]) => [k, String(v)]),
            )
          : undefined,
      );
      return true;
    } catch (err) {
      this.logger.error(
        `Push dispatch failed for user ${notification.userId}: ${err.message}`,
      );
      return false;
    }
  }
}
