require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const admin = require('firebase-admin');

// Initialize Firebase Admin (requires service account JSON)
// You can get this from Firebase Console -> Project Settings -> Service Accounts
const serviceAccount = require('./serviceAccountKey.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
});

const app = express();
const PORT = process.env.PORT || 4000;
const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET || 'relocate_sync_secret';

app.use(bodyParser.json());

/**
 * Webhook Receiver Endpoint
 * Expects POST request from Admin Panel
 */
app.post('/api/webhook/sync', async (req, res) => {
  const { secret, type, payload } = req.body;

  // 1. Validate Secret Token
  if (secret !== WEBHOOK_SECRET) {
    return res.status(401).json({ error: 'Unauthorized: Invalid secret token' });
  }

  console.log(`[Webhook] Received ${type} update:`, payload);

  try {
    // 2. Prepare FCM Message for the Frontend
    const message = {
      topic: 'global_data_sync', // Subscribe frontend clients to this topic
      data: {
        sync_type: type,
        update_time: new Date().toISOString(),
        payload: JSON.stringify(payload)
      },
      notification: {
        title: 'Real-time Update',
        body: `New ${type} update from Admin Panel`
      }
    };

    // 3. Send FCM Notification to Frontend
    const response = await admin.messaging().send(message);
    console.log('[FCM] Successfully sent message:', response);

    // 4. (Optional) Trigger a static build or cache invalidation if hosted on custom server
    // exec('npm run build', (error, stdout, stderr) => { ... });

    res.status(200).json({ message: 'Sync triggered successfully', fcm_response: response });
  } catch (error) {
    console.error('[FCM] Error sending message:', error);
    res.status(500).json({ error: 'Internal server error during FCM sync' });
  }
});

app.listen(PORT, () => {
  console.log(`Webhook Receiver listening at http://localhost:${PORT}`);
  console.log(`Endpoint: http://localhost:${PORT}/api/webhook/sync`);
});
