import { Injectable, OnModuleInit, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as path from 'path';

@Injectable()
export class FirebaseService implements OnModuleInit {
  private readonly logger = new Logger(FirebaseService.name);
  private admin: any = null;

  constructor(private readonly configService: ConfigService) {}

  onModuleInit() {
    const serviceAccountPath = this.configService.get<string>(
      'FIREBASE_SERVICE_ACCOUNT_PATH',
    );

    if (!serviceAccountPath) {
      this.logger.warn('FIREBASE_SERVICE_ACCOUNT_PATH not set — FCM disabled');
      return;
    }

    try {
      // eslint-disable-next-line @typescript-eslint/no-require-imports
      const admin = require('firebase-admin');
      const resolved = path.resolve(serviceAccountPath);
      // eslint-disable-next-line @typescript-eslint/no-require-imports
      const serviceAccount = require(resolved);

      admin.initializeApp({
        credential: admin.credential.cert(serviceAccount),
      });

      this.admin = admin;
      this.logger.log('Firebase Admin SDK initialized');
    } catch (error) {
      this.logger.error('Failed to initialize Firebase Admin SDK', error);
    }
  }

  get isEnabled(): boolean {
    return this.admin !== null;
  }

  async sendPush(
    token: string,
    title: string,
    body: string,
    data?: Record<string, string>,
  ): Promise<boolean> {
    if (!this.admin) return false;

    try {
      await this.admin.messaging().send({
        token,
        notification: { title, body },
        data: data || {},
        webpush: {
          fcmOptions: {
            link: data?.link || '/app',
          },
        },
      });
      return true;
    } catch (error: any) {
      if (
        error?.code === 'messaging/invalid-registration-token' ||
        error?.code === 'messaging/registration-token-not-registered'
      ) {
        this.logger.warn(`Invalid FCM token: ${token.substring(0, 20)}...`);
        return false;
      }
      this.logger.error('FCM send error', error);
      return false;
    }
  }
}
