const webPush = require('web-push');
const mysql = require('mysql2/promise');

// Read arguments from command line
const args = process.argv.slice(2);
const userId = args[0];
const title = args[1];
const body = args[2];
const url = args[3] || '/Capstone_Project/student/dashboard.php';
const activityId = args[4] || null;

const vapidKeys = {
    publicKey: 'BCjNZxc_qk_75lFdUfqp7bzZIzjEBh9BAyJ6yn87bRxRQxHUS-OIS5fvK_No9XEGCkNFJ-9quGaQsHSeHoBKy3Y',
    privateKey: 'VV6asLvFaPIoz-9eXkROjjz7YTWrLqUeXyPqMnMCNkg'
};

webPush.setVapidDetails(
    'mailto:admin@codelab.edu',
    vapidKeys.publicKey,
    vapidKeys.privateKey
);

async function sendPushNotification() {
    try {
        // Connect to database
        const connection = await mysql.createConnection({
            host: 'localhost',
            user: 'root',
            password: '',
            database: 'cpp_learning_system'
        });

        // Get all subscriptions for the user
        const [subscriptions] = await connection.execute(
            'SELECT endpoint, p256dh_key, auth_key FROM push_subscriptions WHERE user_id = ?',
            [userId]
        );

        if (subscriptions.length === 0) {
            console.log('No subscriptions found for user:', userId);
            await connection.end();
            return;
        }

        // Prepare notification payload
        const payload = JSON.stringify({
            title: title,
            body: body,
            url: url,
            activity_id: activityId
        });

        // Send push notification to all user's subscriptions
        const promises = subscriptions.map(async (sub) => {
            const pushSubscription = {
                endpoint: sub.endpoint,
                keys: {
                    p256dh: sub.p256dh_key,
                    auth: sub.auth_key
                }
            };

            try {
                await webPush.sendNotification(pushSubscription, payload);
                console.log('Push sent successfully to:', sub.endpoint.substring(0, 50) + '...');
            } catch (error) {
                console.error('Error sending push:', error);
                // If subscription is invalid, remove it from database
                if (error.statusCode === 410 || error.statusCode === 404) {
                    await connection.execute(
                        'DELETE FROM push_subscriptions WHERE endpoint = ?',
                        [sub.endpoint]
                    );
                    console.log('Removed invalid subscription');
                }
            }
        });

        await Promise.all(promises);
        await connection.end();
        console.log('Push notifications sent successfully');
    } catch (error) {
        console.error('Error:', error);
        process.exit(1);
    }
}

sendPushNotification();
