import admin from 'firebase-admin';
import axios from 'axios';
import moment from 'moment';
import dotenv from 'dotenv';

dotenv.config();

// Initialize Firebase Admin SDK
admin.initializeApp({
    credential: admin.credential.cert(process.env.FIREBASE_CREDENTIALS),
    databaseURL: process.env.FIREBASE_DATABASE_URL,
});

const db = admin.database();

// ✅ MAIN FUNCTION: Schedule notifications per contact
const scheduleNotifications = async () => {
    try {
        console.log("🔄 Starting per-contact scheduling process...");

        const usersSnapshot = await db.ref('users').once('value');
        const eventsSnapshot = await db.ref('events').once('value');

        const users = usersSnapshot.val();
        const events = eventsSnapshot.val();

        if (!users || !events) {
            console.log("⚠️ No users or events found.");
            return;
        }

        for (const eventId in events) {
            const eventData = events[eventId];
            if (eventData.status !== 1) continue;

            const userId = eventData.userId;
            const user = users[userId];
            if (!user || !user.EmergencyContacts) continue;

            // Ensure EmergencyContacts is an array
            const contacts = Array.isArray(user.EmergencyContacts)
                ? user.EmergencyContacts
                : Object.values(user.EmergencyContacts);

            const eventTime = eventData.updatedAt + (eventData.hour * 3600) + (eventData.minute * 60); // in seconds
            const currentTime = moment().unix();

            for (const contact of contacts) {
                const priority = contact.priority || 1;
                const contactWaitInMin = (user.wait || 2) * priority;
                const notifyAt = eventTime + contactWaitInMin * 60;
                const delay = (notifyAt - currentTime) * 1000;

                if (delay <= 0) {
                    console.log(`⚠️ Contact ${contact.name} already due. Sending immediately.`);
                    triggerSingleNotification(eventId, eventData, user, users, contact);
                } else {
                    console.log(`⏰ Scheduling contact ${contact.name} (priority ${priority}) in ${Math.round(delay / 1000)}s`);
                    setTimeout(() => {
                        triggerSingleNotification(eventId, eventData, user, users, contact);
                    }, delay);
                }
            }
        }
    } catch (err) {
        console.error("❌ Error in scheduling per contact:", err);
    }
};

// ✅ Send notification to a single contact
const triggerSingleNotification = async (eventId, eventData, user, allUsers, contact) => {
    const fcmToken = allUsers[contact.userUID]?.fcmToken;
    if (!fcmToken) {
        console.log(`🚫 No FCM token for contact ${contact.name}`);
        return;
    }

    const currentPriority = contact.priority || 1;
    if ((eventData.last_sent_priority || 0) >= currentPriority) {
        console.log(`🔕 Already notified priority ${eventData.last_sent_priority}, skipping contact ${contact.name}`);
        return;
    }

    const message = `🚨 Your contact ${user.name} may need help!`;
    await sendNotification(fcmToken, message);

    console.log(`✅ Notification sent to contact ${contact.name} (priority ${currentPriority})`);

    await db.ref(`events/${eventId}/last_sent_priority`).set(currentPriority);
};

// ✅ Send FCM Notification
const sendNotification = async (fcmToken, message) => {
    try {
        const accessToken = await admin.credential.cert(process.env.FIREBASE_CREDENTIALS).getAccessToken();
        const projectId = process.env.FIREBASE_PROJECT_ID;

        const response = await axios.post(
            `https://fcm.googleapis.com/v1/projects/${projectId}/messages:send`,
            {
                message: {
                    token: fcmToken,
                    notification: {
                        title: 'Emergency Alert 🚨',
                        body: message,
                    },
                    android: {
                        priority: 'high',
                    },
                    apns: {
                        headers: {
                            'apns-priority': '10',
                        },
                    },
                },
            },
            {
                headers: {
                    Authorization: `Bearer ${accessToken.access_token}`,
                    'Content-Type': 'application/json',
                },
            }
        );

        console.log('📨 FCM Notification Sent:', response.data);
    } catch (error) {
        console.log('❌ FCM Notification Failed:', error.response?.data?.error?.details || error.message);
    }
};

// ✅ Start scheduling
scheduleNotifications();
