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

export interface SaveTokenDto {
    token: string;
    platform: 'web' | 'android' | 'ios';
    userId: string;
}

@Injectable()
export class FcmTokensService implements OnModuleInit {
    private readonly logger = new Logger(FcmTokensService.name);

    constructor(
        private configService: ConfigService,
        private httpService: HttpService,
    ) { }

    onModuleInit() {
        this.initializeFirebase();
    }

    private initializeFirebase() {
        const serviceAccountPath = this.configService.get<string>('FIREBASE_ADMIN_SDK_PATH');

        // Check if already initialized to avoid error
        if (admin.apps.length > 0) {
            this.logger.log('Firebase Admin already initialized');
            return;
        }

        const certPath = serviceAccountPath || process.env.FIREBASE_SERVICE_ACCOUNT || '';
        if (certPath) {
            try {
                // Simplified init - in prod use cert() with service account object
                // This is "showing how to configure"
                const cert = require(certPath);
                admin.initializeApp({
                    credential: admin.credential.cert(cert),
                });
                this.logger.log('Firebase Admin initialized successfully');
            } catch (error) {
                this.logger.warn('Failed to initialize Firebase Admin: ' + error.message);
            }
        } else {
            this.logger.warn('FIREBASE_ADMIN_SDK_PATH not set, skipping Firebase Admin init');
        }
    }

    async saveToken(dto: SaveTokenDto): Promise<void> {
        try {
            // Logic to UPSERT token. 
            // Option 1: Direct DB access (if shared)
            // Option 2: Call Core API (Recommended for microservices)

            const coreUrl = this.configService.get<string>('CORE_API_URL');
            if (coreUrl) {
                await firstValueFrom(
                    this.httpService.post(`${coreUrl}/api/v1/tokens`, {
                        token: dto.token,
                        platform: dto.platform,
                    }, {
                        // Assuming we need to forward auth or use a system token
                        // For now, logging call
                    })
                );
                this.logger.log(`Token saved for user ${dto.userId} via Core API`);
            } else {
                // Mock behavior
                this.logger.log(`[MOCK] Saved FCM token for user ${dto.userId}: ${dto.token.substring(0, 10)}...`);
            }
        } catch (error) {
            this.logger.error(`Error saving token: ${error.message}`);
            throw error;
        }
    }

    // Future method to send notification
    async sendNotification(token: string, title: string, body: string) {
        if (admin.apps.length === 0) return;

        try {
            await admin.messaging().send({
                token,
                notification: { title, body },
            });
        } catch (error) {
            if (error.code === 'messaging/registration-token-not-registered') {
                // Handle invalid token (cleanup)
                this.logger.warn('Token invalid/expired, should perform cleanup');
            }
        }
    }
}
