import { Injectable } from '@nestjs/common';
import {
  applicationDefault,
  cert,
  getApps,
  initializeApp,
} from 'firebase-admin/app';
import { getMessaging } from 'firebase-admin/messaging';

@Injectable()
export class FirebasePushGateway {
  private credential() {
    const json = process.env.FIREBASE_SERVICE_ACCOUNT_JSON;
    if (!json?.trim()) return applicationDefault();
    try {
      return cert(JSON.parse(json));
    } catch {
      // Never include credential contents in errors or logs.
      throw new Error('Invalid FIREBASE_SERVICE_ACCOUNT_JSON configuration.');
    }
  }

  async send(token: string, notificationId: number, userId: number) {
    const app =
      getApps().find((app) => app.name === 'mis-mobile') ??
      initializeApp(
        {
          credential: this.credential(),
          projectId: process.env.FIREBASE_PROJECT_ID,
        },
        'mis-mobile',
      );
    // Keep lock-screen content generic; detail always rechecks current API access.
    return getMessaging(app).send({
      token,
      notification: { title: 'GPSF-MIS', body: 'You have a new notification.' },
      data: { notificationId: String(notificationId), userId: String(userId) },
      android: {
        priority: 'high',
        ttl: 3600000,
        notification: {
          channelId: 'mis_notifications',
          tag: `mis-${notificationId}`,
          icon: 'ic_stat_notification',
        },
      },
      apns: {
        headers: {
          'apns-push-type': 'alert',
          'apns-priority': '10',
          'apns-expiration': String(Math.floor(Date.now() / 1000) + 3600),
          'apns-collapse-id': `mis-${notificationId}`,
        },
        payload: { aps: { sound: 'default' } },
      },
    });
  }
}
