import admin from 'firebase-admin';
import prisma from './prisma.js';
import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, resolve } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// Initialize Firebase Admin SDK
let firebaseInitialized = false;

export function initializeFirebase() {
  if (firebaseInitialized) {
    return;
  }

  // Check if Firebase credentials are available
  const serviceAccountPath = process.env.FIREBASE_SERVICE_ACCOUNT_PATH;
  const firebaseProjectId = process.env.FIREBASE_PROJECT_ID;
  const firebaseServiceAccountJson = process.env.FIREBASE_SERVICE_ACCOUNT_JSON;

  if (!serviceAccountPath && !firebaseProjectId && !firebaseServiceAccountJson) {
    console.warn('[FCM] Firebase credentials not configured. Push notifications will be disabled.');
    console.warn('[FCM] Set FIREBASE_SERVICE_ACCOUNT_PATH, FIREBASE_PROJECT_ID, or FIREBASE_SERVICE_ACCOUNT_JSON');
    return;
  }

  try {
    if (serviceAccountPath) {
      // Initialize with service account file path
      const fullPath = resolve(__dirname, '..', '..', serviceAccountPath);
      const serviceAccount = JSON.parse(readFileSync(fullPath, 'utf8'));
      admin.initializeApp({
        credential: admin.credential.cert(serviceAccount),
      });
    } else if (firebaseServiceAccountJson) {
      // Initialize with service account JSON string
      const serviceAccount = JSON.parse(firebaseServiceAccountJson);
      admin.initializeApp({
        credential: admin.credential.cert(serviceAccount),
      });
    } else if (firebaseProjectId) {
      // Initialize with default credentials (for cloud environments like GCP)
      admin.initializeApp({
        projectId: firebaseProjectId,
      });
    }

    firebaseInitialized = true;
    console.log('[FCM] Firebase Admin SDK initialized successfully');
  } catch (error) {
    console.error('[FCM] Failed to initialize Firebase Admin SDK:', error);
    console.error('[FCM] Push notifications will be disabled');
  }
}

/**
 * Send FCM push notification to a user's devices
 * @param userId - The user ID to send notification to
 * @param title - Notification title
 * @param body - Notification body
 * @param data - Additional data payload
 * @returns Promise<boolean> - true if at least one notification was sent successfully
 */
export async function sendFCMNotification(
  userId: string,
  title: string,
  body: string,
  data?: Record<string, string>
): Promise<boolean> {
  if (!firebaseInitialized) {
    console.warn('[FCM] Firebase not initialized, skipping notification');
    return false;
  }

  try {
    // Get all FCM tokens for the user
    const devices = await prisma.userDevice.findMany({
      where: {
        userId,
        fcmToken: { not: null },
      },
      select: {
        fcmToken: true,
        platform: true,
      },
    });

    if (devices.length === 0) {
      console.log(`[FCM] No FCM tokens found for user ${userId}`);
      return false;
    }

    const tokens = devices.map((d) => d.fcmToken!).filter(Boolean);
    if (tokens.length === 0) {
      return false;
    }

    // Prepare notification payload
    const message: admin.messaging.MulticastMessage = {
      notification: {
        title,
        body,
      },
      data: data || {},
      tokens,
      // Let the client SDK use its default notification channel and icon.
      android: {
        priority: 'high' as const,
        notification: {
          sound: 'default',
        },
      },
      apns: {
        payload: {
          aps: {
            sound: 'default',
            badge: 1,
          },
        },
      },
    };

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

    // Remove invalid tokens
    if (response.failureCount > 0) {
      const failedTokens: string[] = [];
      response.responses.forEach((resp, idx) => {
        if (!resp.success && resp.error) {
          const errorCode = resp.error.code;
          if (
            errorCode === 'messaging/invalid-registration-token' ||
            errorCode === 'messaging/registration-token-not-registered'
          ) {
            failedTokens.push(tokens[idx]);
          }
        }
      });

      // Remove invalid tokens from database
      if (failedTokens.length > 0) {
        await prisma.userDevice.updateMany({
          where: {
            userId,
            fcmToken: { in: failedTokens },
          },
          data: {
            fcmToken: null,
          },
        });
        console.log(`[FCM] Removed ${failedTokens.length} invalid FCM tokens for user ${userId}`);
      }
    }

    const successCount = response.successCount;
    console.log(
      `[FCM] Sent notification to user ${userId}: ${successCount}/${tokens.length} successful`
    );

    return successCount > 0;
  } catch (error) {
    console.error(`[FCM] Error sending notification to user ${userId}:`, error);
    return false;
  }
}

/**
 * Send a message notification to a user
 */
export async function sendMessageNotification(
  recipientId: string,
  senderName: string,
  messageContent: string,
  conversationId: string,
  propertyTitle?: string
): Promise<boolean> {
  const title = propertyTitle ? `New message about ${propertyTitle}` : 'New message';
  const body = `${senderName}: ${messageContent.substring(0, 100)}${messageContent.length > 100 ? '...' : ''}`;

  return sendFCMNotification(recipientId, title, body, {
    type: 'message',
    conversationId,
    senderName,
  });
}

