import admin, { type ServiceAccount } from "firebase-admin";
import dotenv from "dotenv";
dotenv.config();

const serviceAccount = {
    project_id: process.env.FCM_PROJECT_ID,
    private_key_id: process.env.FCM_PROJECT_KEY_ID,
    client_email: process.env.FCM_PROJECT_CLIENT_EMAIL,
    private_key: process.env.FCM_PROJECT_PRIVATE_KEY ? process.env.FCM_PROJECT_PRIVATE_KEY.replace(/\\n/g, '\n') : undefined
};

// Fail fast
if (!serviceAccount.project_id) {
    throw new Error("❌ FIREBASE_PROJECT_ID is missing");
}

if (!admin.apps.length) {
    admin.initializeApp({
        credential: admin.credential.cert(
            serviceAccount as unknown as ServiceAccount
        ),
    });
}

export const sendNotification = async (
    tokens: string[],
    title: string,
    body: string,
    data: Record<string, string> = {}
) => {
    if (!tokens || tokens.length === 0) return;

    if (!admin.apps.length) {
        throw new Error("Firebase Admin not initialized");
    }

    const message = {
        tokens,
        notification: {
            title,
            body,
        },
        data,
    };

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

    const invalidTokens: string[] = [];
    response.responses.forEach((res, index) => {
        if (!res.success) {
            const errorCode = res.error?.code;

            if (
                errorCode === "messaging/registration-token-not-registered" ||
                errorCode === "messaging/invalid-registration-token"
            ) {
                invalidTokens.push(tokens[index]);
            }
        }
    });

    return {
        successCount: response.successCount,
        failureCount: response.failureCount,
        invalidTokens,
    };
};