const express = require('express');
const router = express.Router();
const db = require('../config/database');
const admin = require('firebase-admin');

const STATIC_ALERT_FCM_TOKEN = (process.env.STATIC_ALERT_FCM_TOKEN || process.env.ALERT_TEST_FCM_TOKEN || '').trim();

// Send high alert notification to a parent
// POST /api/notification/send-alert
router.post('/send-alert', async (req, res) => {
  try {
    const { 
      parent_id,      // Target parent user ID (optional when child/device provided)
      child_id,       // Child ID (optional)
      device_id,      // Device ID (optional)
      alert_type,     // 'high_alert', 'medium_alert', 'low_alert'
      title,          // Notification title
      message,        // Notification message/body
      extra_data      // Additional data (optional)
    } = req.body;

    if (!alert_type || !title || !message) {
      return res.status(400).json({ 
        success: false,
        message: 'alert_type, title, and message are required' 
      });
    }

    // Validate alert_type
    const validAlertTypes = ['high_alert', 'medium_alert', 'low_alert', 'position_lock_violation', 'geofence_alert', 'sos_alert'];
    if (!validAlertTypes.includes(alert_type)) {
      return res.status(400).json({ 
        success: false,
        message: `Invalid alert_type. Must be one of: ${validAlertTypes.join(', ')}` 
      });
    }

    // Resolve parent/child/device relationship automatically
    let resolvedParentId = parent_id;
    let resolvedChildId = child_id;
    let resolvedDeviceId = device_id;

    if (!resolvedParentId && resolvedChildId) {
      const [childRows] = await db.execute(
        'SELECT parent_id, device_id FROM children WHERE id = ? LIMIT 1',
        [resolvedChildId]
      );

      if (childRows.length > 0) {
        resolvedParentId = childRows[0].parent_id || resolvedParentId;
        resolvedDeviceId = resolvedDeviceId || childRows[0].device_id;
      }
    }

    if ((!resolvedParentId || !resolvedChildId) && resolvedDeviceId) {
      const [deviceRows] = await db.execute(
        'SELECT id as child_id, parent_id FROM children WHERE device_id = ? LIMIT 1',
        [resolvedDeviceId]
      );

      if (deviceRows.length > 0) {
        resolvedParentId = resolvedParentId || deviceRows[0].parent_id;
        resolvedChildId = resolvedChildId || deviceRows[0].child_id;
      }
    }

    if (!resolvedParentId) {
      return res.status(404).json({
        success: false,
        message: 'Unable to locate parent for this alert. Provide parent_id or valid child/device reference.',
        debug: {
          parent_id,
          child_id,
          device_id,
          resolved_parent_id: resolvedParentId
        }
      });
    }

    // Resolve FCM token (allow static override via env)
    let fcmToken = STATIC_ALERT_FCM_TOKEN || null;
    let tokenSource = 'static_env';
    let sessionDebug = null;

    if (!fcmToken) {
      tokenSource = 'user_session';
      const [sessions] = await db.execute(
        'SELECT fcm_token FROM user_sessions WHERE user_id = ? AND fcm_token IS NOT NULL ORDER BY created_at DESC LIMIT 1',
        [resolvedParentId]
      );

      sessionDebug = {
        parent_id: resolvedParentId,
        sessions_found: sessions.length,
        has_token: sessions.length > 0 ? !!sessions[0].fcm_token : false,
        token_preview: sessions.length > 0 && sessions[0].fcm_token ? sessions[0].fcm_token.substring(0, 10) + '...' : null
      };

      if (sessions.length === 0 || !sessions[0].fcm_token) {
        return res.status(404).json({ 
          success: false,
          message: 'No FCM token found for this parent. Parent may not be logged in.',
          debug: sessionDebug
        });
      }

      fcmToken = sessions[0].fcm_token;
    }

    // Get child name if child_id provided
    let childName = null;
    if (resolvedChildId) {
      const [children] = await db.execute(
        'SELECT first_name, last_name FROM children WHERE id = ?',
        [resolvedChildId]
      );
      if (children.length > 0) {
        childName = `${children[0].first_name} ${children[0].last_name}`;
      }
    }

    // Build FCM message - DATA ONLY for high alerts (ensures onMessageReceived is called)
    const fcmMessage = {
      data: {
        type: 'alert_notification',
        alert_type: alert_type,
        title: title,
        body: message,
        child_id: resolvedChildId ? String(resolvedChildId) : '',
        child_name: childName || '',
        device_id: resolvedDeviceId ? String(resolvedDeviceId) : '',
        timestamp: new Date().toISOString(),
        play_siren: alert_type === 'high_alert' || alert_type === 'sos_alert' ? 'true' : 'false',
        ...(extra_data || {})
      },
      android: {
        priority: 'high',
        ttl: 60 * 1000 // 1 minute TTL
      },
      token: fcmToken
    };

    // Send the notification
    const response = await admin.messaging().send(fcmMessage);
    console.log('High alert notification sent successfully:', response);

    // Log notification to database
    try {
      await db.execute(
        `INSERT INTO notifications (user_id, child_id, device_id, alert_type, title, message, fcm_message_id, status, created_at)
         VALUES (?, ?, ?, ?, ?, ?, ?, 'sent', NOW())`,
        [resolvedParentId, resolvedChildId || null, resolvedDeviceId || null, alert_type, title, message, response]
      );
    } catch (logError) {
      console.log('Could not log notification (table may not exist):', logError.message);
    }

    res.json({ 
      success: true,
      message: 'Alert notification sent successfully',
      fcm_message_id: response,
      debug: {
        parent_id: resolvedParentId,
        child_id: resolvedChildId,
        device_id: resolvedDeviceId,
        fcm_token_preview: fcmToken.substring(0, 10) + '...',
        fcm_token_length: fcmToken.length
      }
    });

  } catch (error) {
    console.error('Error sending alert notification:', error);
    
    // Handle specific FCM errors
    if (error.code === 'messaging/invalid-registration-token' || 
        error.code === 'messaging/registration-token-not-registered') {
      return res.status(400).json({ 
        success: false,
        message: 'Invalid or expired FCM token. Parent needs to re-login.' 
      });
    }

    res.status(500).json({ 
      success: false,
      message: 'Failed to send notification: ' + error.message 
    });
  }
});

// Send high alert to multiple parents (batch)
// POST /api/notification/send-batch-alert
router.post('/send-batch-alert', async (req, res) => {
  try {
    const { 
      parent_ids,     // Array of parent user IDs
      alert_type,
      title,
      message,
      extra_data
    } = req.body;

    if (!parent_ids || !Array.isArray(parent_ids) || parent_ids.length === 0) {
      return res.status(400).json({ 
        success: false,
        message: 'parent_ids must be a non-empty array' 
      });
    }

    if (!alert_type || !title || !message) {
      return res.status(400).json({ 
        success: false,
        message: 'alert_type, title, and message are required' 
      });
    }

    // Get FCM tokens for all parents
    const placeholders = parent_ids.map(() => '?').join(',');
    const [sessions] = await db.execute(
      `SELECT user_id, fcm_token FROM user_sessions 
       WHERE user_id IN (${placeholders}) AND fcm_token IS NOT NULL`,
      parent_ids
    );

    if (sessions.length === 0) {
      return res.status(404).json({ 
        success: false,
        message: 'No FCM tokens found for any of the specified parents' 
      });
    }

    const tokens = sessions.map(s => s.fcm_token);

    // Build multicast message
    const multicastMessage = {
      data: {
        type: 'alert_notification',
        alert_type: alert_type,
        title: title,
        body: message,
        timestamp: new Date().toISOString(),
        play_siren: alert_type === 'high_alert' || alert_type === 'sos_alert' ? 'true' : 'false',
        ...(extra_data || {})
      },
      android: {
        priority: 'high',
        ttl: 60 * 1000
      },
      tokens: tokens
    };

    // Send to multiple devices
    const response = await admin.messaging().sendEachForMulticast(multicastMessage);
    
    console.log(`Batch alert sent: ${response.successCount} success, ${response.failureCount} failures`);

    res.json({ 
      success: true,
      message: 'Batch alert sent',
      total_tokens: tokens.length,
      success_count: response.successCount,
      failure_count: response.failureCount
    });

  } catch (error) {
    console.error('Error sending batch alert:', error);
    res.status(500).json({ 
      success: false,
      message: 'Failed to send batch notification: ' + error.message 
    });
  }
});

// Send SOS alert (highest priority - always plays siren)
// POST /api/notification/send-sos
router.post('/send-sos', async (req, res) => {
  try {
    const { 
      parent_id,
      child_id,
      device_id,
      location,        // { latitude, longitude, address }
      message
    } = req.body;

    if (!parent_id && !child_id && !device_id) {
      return res.status(400).json({ 
        success: false,
        message: 'Provide at least parent_id, child_id, or device_id to send SOS alert.' 
      });
    }

    let resolvedParentId = parent_id;
    let resolvedChildId = child_id;
    let resolvedDeviceId = device_id;

    if (!resolvedParentId && resolvedChildId) {
      const [childRows] = await db.execute(
        'SELECT parent_id, device_id FROM children WHERE id = ? LIMIT 1',
        [resolvedChildId]
      );
      if (childRows.length > 0) {
        resolvedParentId = childRows[0].parent_id || resolvedParentId;
        resolvedDeviceId = resolvedDeviceId || childRows[0].device_id;
      }
    }

    if ((!resolvedParentId || !resolvedChildId) && resolvedDeviceId) {
      const [deviceRows] = await db.execute(
        'SELECT id as child_id, parent_id FROM children WHERE device_id = ? LIMIT 1',
        [resolvedDeviceId]
      );
      if (deviceRows.length > 0) {
        resolvedParentId = resolvedParentId || deviceRows[0].parent_id;
        resolvedChildId = resolvedChildId || deviceRows[0].child_id;
      }
    }

    if (!resolvedParentId) {
      return res.status(404).json({
        success: false,
        message: 'Unable to locate parent for SOS alert. Provide parent_id or valid child/device reference.',
        debug: {
          parent_id,
          child_id,
          device_id,
          resolved_parent_id: resolvedParentId
        }
      });
    }

    // Resolve FCM token with static override option
    let fcmToken = STATIC_ALERT_FCM_TOKEN || null;
    let tokenSource = 'static_env';
    let sessionDebug = null;

    if (!fcmToken) {
      tokenSource = 'user_session';
      const [sessions] = await db.execute(
        'SELECT fcm_token FROM user_sessions WHERE user_id = ? AND fcm_token IS NOT NULL ORDER BY created_at DESC LIMIT 1',
        [resolvedParentId]
      );

      sessionDebug = {
        parent_id: resolvedParentId,
        sessions_found: sessions.length,
        has_token: sessions.length > 0 ? !!sessions[0].fcm_token : false,
        token_preview: sessions.length > 0 && sessions[0].fcm_token ? sessions[0].fcm_token.substring(0, 10) + '...' : null
      };

      if (sessions.length === 0 || !sessions[0].fcm_token) {
        return res.status(404).json({ 
          success: false,
          message: 'No FCM token found for this parent',
          debug: sessionDebug
        });
      }

      fcmToken = sessions[0].fcm_token;
    }

    // Get child name
    let childName = 'Your child';
    if (resolvedChildId) {
      const [children] = await db.execute(
        'SELECT first_name, last_name FROM children WHERE id = ?',
        [resolvedChildId]
      );
      if (children.length > 0) {
        childName = `${children[0].first_name} ${children[0].last_name}`;
      }
    }

    // Build SOS message
    const fcmMessage = {
      data: {
        type: 'sos_alert',
        alert_type: 'sos_alert',
        title: '🚨 SOS EMERGENCY ALERT',
        body: message || `${childName} triggered an SOS alert!`,
        child_id: resolvedChildId ? String(resolvedChildId) : '',
        child_name: childName,
        device_id: resolvedDeviceId ? String(resolvedDeviceId) : '',
        latitude: location?.latitude ? String(location.latitude) : '',
        longitude: location?.longitude ? String(location.longitude) : '',
        address: location?.address || '',
        timestamp: new Date().toISOString(),
        play_siren: 'true',
        priority: 'critical'
      },
      android: {
        priority: 'high',
        ttl: 0 // Immediate delivery
      },
      token: fcmToken
    };

    const response = await admin.messaging().send(fcmMessage);
    console.log('SOS alert sent:', response);

    res.json({ 
      success: true,
      message: 'SOS alert sent successfully',
      fcm_message_id: response,
      debug: {
        parent_id: resolvedParentId,
        child_id: resolvedChildId,
        device_id: resolvedDeviceId,
        token_source: tokenSource,
        fcm_token_preview: fcmToken.substring(0, 10) + '...'
      }
    });

  } catch (error) {
    console.error('Error sending SOS alert:', error);
    res.status(500).json({ 
      success: false,
      message: 'Failed to send SOS alert: ' + error.message 
    });
  }
});

// Test endpoint - Send test alert to yourself
// POST /api/notification/test-alert
router.post('/test-alert', async (req, res) => {
  try {
    const { alert_type = 'high_alert', parent_id, child_id, device_id } = req.body;

    if (!parent_id && !child_id && !device_id && !STATIC_ALERT_FCM_TOKEN) {
      return res.status(400).json({
        success: false,
        message: 'Provide parent_id, child_id, device_id, or configure STATIC_ALERT_FCM_TOKEN to send a test alert.'
      });
    }

    let resolvedParentId = parent_id;
    let resolvedChildId = child_id;
    let resolvedDeviceId = device_id;

    if (!resolvedParentId && resolvedChildId) {
      const [childRows] = await db.execute(
        'SELECT parent_id, device_id FROM children WHERE id = ? LIMIT 1',
        [resolvedChildId]
      );
      if (childRows.length > 0) {
        resolvedParentId = childRows[0].parent_id || resolvedParentId;
        resolvedDeviceId = resolvedDeviceId || childRows[0].device_id;
      }
    }

    if ((!resolvedParentId || !resolvedChildId) && resolvedDeviceId) {
      const [deviceRows] = await db.execute(
        'SELECT id as child_id, parent_id FROM children WHERE device_id = ? LIMIT 1',
        [resolvedDeviceId]
      );
      if (deviceRows.length > 0) {
        resolvedParentId = resolvedParentId || deviceRows[0].parent_id;
        resolvedChildId = resolvedChildId || deviceRows[0].child_id;
      }
    }

    // Resolve FCM token with static override option
    let fcmToken = STATIC_ALERT_FCM_TOKEN || null;
    let sessionDebug = null;

    if (!fcmToken) {
      if (!resolvedParentId) {
        return res.status(404).json({
          success: false,
          message: 'Unable to find parent for test alert. Provide parent_id or valid child/device reference.'
        });
      }

      const [sessions] = await db.execute(
        'SELECT fcm_token FROM user_sessions WHERE user_id = ? AND fcm_token IS NOT NULL ORDER BY created_at DESC LIMIT 1',
        [resolvedParentId]
      );

      sessionDebug = {
        parent_id: resolvedParentId,
        sessions_found: sessions.length,
        has_token: sessions.length > 0 ? !!sessions[0].fcm_token : false,
        token_preview: sessions.length > 0 && sessions[0].fcm_token ? sessions[0].fcm_token.substring(0, 10) + '...' : null
      };

      if (sessions.length === 0 || !sessions[0].fcm_token) {
        return res.status(404).json({
          success: false,
          message: 'No FCM token found. Please re-login to the app.',
          debug: sessionDebug
        });
      }

      fcmToken = sessions[0].fcm_token;
    }

    const fcmMessage = {
      data: {
        type: 'test_alert',
        alert_type: alert_type,
        title: '🔔 Test Alert',
        body: `This is a test ${alert_type} notification`,
        child_id: resolvedChildId ? String(resolvedChildId) : '',
        device_id: resolvedDeviceId ? String(resolvedDeviceId) : '',
        timestamp: new Date().toISOString(),
        play_siren: alert_type === 'high_alert' ? 'true' : 'false'
      },
      android: {
        priority: 'high'
      },
      token: fcmToken
    };

    const response = await admin.messaging().send(fcmMessage);
    console.log('Test alert sent:', response);

    res.json({ 
      success: true,
      message: 'Test alert sent successfully',
      alert_type: alert_type,
      fcm_message_id: response,
      debug: {
        parent_id: resolvedParentId,
        child_id: resolvedChildId,
        device_id: resolvedDeviceId,
        fcm_token_preview: fcmToken.substring(0, 10) + '...'
      }
    });

  } catch (error) {
    console.error('Error sending test alert:', error);
    res.status(500).json({ 
      success: false,
      message: 'Failed to send test alert: ' + error.message 
    });
  }
});

module.exports = router;
