import admin from "firebase-admin";

// Inisialisasi admin (hanya sekali)
if (!admin.apps.length) {
   admin.initializeApp({
      credential: admin.credential.cert({
         projectId: process.env.GOOGLE_PROJECT_ID,
         privateKey: process.env.GOOGLE_PRIVATE_KEY?.replace(/\\n/g, '\n'),
         clientEmail: process.env.GOOGLE_CLIENT_EMAIL,
      }),
   });
}

/**
 * Kirim push notifikasi ke FCM token
 */
export async function sendFCM(token: string[], title: string, body: string) {
   const message = {
      notification: {
         title,
         body,
      },
      data: {
         id: 'cm1eqwkwj00067j2bzejyh9u7',
         category: 'division',
         content: 'cm1eqwkvu00017j2b8qnisp9g',
      },
      apns: {
         payload: {
            aps: {
               contentAvailable: true,
               alert: {
                  title,
                  body,
               },
            },
         },
      },
      token,
   };

   try {
      const result = await admin.messaging().sendEachForMulticast({
         tokens: token,
         ...message,
      })
      if (result.failureCount > 0) {
         const failedTokens: any[] = [];
         result.responses.forEach((resp, idx) => {
            if (!resp.success) {
               failedTokens.push(token[idx]);
            }
         });
         // const deleteToken = await prisma.tokenDeviceUser.deleteMany({
         //    where: {
         //       token: {
         //          in: failedTokens
         //       }
         //    }
         // });
      }
   } catch (err) {
      console.error("❌ Gagal mengirim FCM:", err);
   }
}