
import admin from '../config/firebase/Firebase';
import User from '../models/users';
import { IUserDocument } from '../models/users';
import { MulticastMessage, BatchResponse, SendResponse } from 'firebase-admin/messaging';
interface PushResult {
  success: boolean;
  sent: number;
  failed: number;
}

export async function sendPushNotification(
  userId: string,
  title: string,
  message: string,
  type: string,
  data: Record<string, string> = {}
): Promise<PushResult> {
  try {
    const user: IUserDocument | null = await User.findById(userId).select('deviceTokens');
    if (!user || !user.deviceTokens || user.deviceTokens.length === 0) {
      return { success: true, sent: 0, failed: 0 };
    }

    const tokens = user.deviceTokens.map(dt => dt.token).filter(Boolean);
    if (tokens.length === 0) {
      return { success: true, sent: 0, failed: 0 };
    }

    const payload: MulticastMessage = {
      tokens,
      notification: {
        title,
        body: message,
      },
      data: {
        type,
        ...data,
      },
    };

    const response: BatchResponse = await admin.messaging().sendEachForMulticast(payload);

    // Remove invalid/unregistered tokens
    const invalidTokens: string[] = [];
    response.responses.forEach((result: SendResponse, idx: number) => {
      const error = result.error;
      if (error && (
        error.code === 'messaging/invalid-registration-token' ||
        error.code === 'messaging/registration-token-not-registered'
      )) {
        invalidTokens.push(tokens[idx]);
      }
    });
    if (invalidTokens.length > 0) {
      await User.updateOne(
        { _id: userId },
        { $pull: { deviceTokens: { token: { $in: invalidTokens } } } }
      );
    }

    const sent = response.responses.filter((r: SendResponse) => !r.error).length;
    const failed = response.responses.filter((r: SendResponse) => r.error).length;
    return { success: true, sent, failed };
  } catch (error) {
    // Optionally log error
    return { success: false, sent: 0, failed: 0 };
  }
}
