const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const { supabase } = require('../config/supabase');

/**
 * Middleware to verify JWT token
 */
function authMiddleware(req, res, next) {
  const authHeader = req.headers.authorization;
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'No token provided' });
  }

  try {
    const token = authHeader.split(' ')[1];
    req.user = jwt.verify(token, process.env.JWT_SECRET);
    next();
  } catch (err) {
    return res.status(401).json({ error: 'Invalid token' });
  }
}

// Apply auth middleware to all routes
router.use(authMiddleware);

/**
 * GET /api/notification-settings
 * Returns notification settings for current user
 */
router.get('/', async (req, res) => {
  try {
    const userId = req.user.userId;

    // Get settings or return defaults
    const { data: settings, error } = await supabase
      .from('notification_settings')
      .select('*')
      .eq('user_id', userId)
      .single();

    if (error && error.code !== 'PGRST116') { // PGRST116 = no rows returned
      console.error('Get notification settings error:', error);
      return res.status(500).json({ error: 'Failed to get notification settings' });
    }

    // Return settings or defaults
    res.json({
      settings: settings ? {
        notifyNoActivity: settings.notify_no_activity,
        notifyUnusualPattern: settings.notify_unusual_pattern,
        notifySensorOffline: settings.notify_sensor_offline,
        notifyWeeklyReport: settings.notify_weekly_report,
        noActivityHours: settings.no_activity_hours,
        quietHoursEnabled: settings.quiet_hours_enabled,
        quietHoursStart: settings.quiet_hours_start,
        quietHoursEnd: settings.quiet_hours_end,
        pushEnabled: settings.push_enabled,
        emailEnabled: settings.email_enabled
      } : {
        // Defaults
        notifyNoActivity: true,
        notifyUnusualPattern: true,
        notifySensorOffline: true,
        notifyWeeklyReport: true,
        noActivityHours: 6,
        quietHoursEnabled: false,
        quietHoursStart: '22:00',
        quietHoursEnd: '07:00',
        pushEnabled: true,
        emailEnabled: true
      }
    });

  } catch (error) {
    console.error('Get notification settings error:', error);
    res.status(500).json({ error: error.message });
  }
});

/**
 * PATCH /api/notification-settings
 * Updates notification settings
 */
router.patch('/', async (req, res) => {
  try {
    const userId = req.user.userId;
    const {
      notifyNoActivity,
      notifyUnusualPattern,
      notifySensorOffline,
      notifyWeeklyReport,
      noActivityHours,
      quietHoursEnabled,
      quietHoursStart,
      quietHoursEnd,
      pushEnabled,
      emailEnabled
    } = req.body;

    // Build update data
    const updateData = {
      user_id: userId,
      updated_at: new Date().toISOString()
    };

    if (notifyNoActivity !== undefined) updateData.notify_no_activity = notifyNoActivity;
    if (notifyUnusualPattern !== undefined) updateData.notify_unusual_pattern = notifyUnusualPattern;
    if (notifySensorOffline !== undefined) updateData.notify_sensor_offline = notifySensorOffline;
    if (notifyWeeklyReport !== undefined) updateData.notify_weekly_report = notifyWeeklyReport;
    if (noActivityHours !== undefined) updateData.no_activity_hours = noActivityHours;
    if (quietHoursEnabled !== undefined) updateData.quiet_hours_enabled = quietHoursEnabled;
    if (quietHoursStart !== undefined) updateData.quiet_hours_start = quietHoursStart;
    if (quietHoursEnd !== undefined) updateData.quiet_hours_end = quietHoursEnd;
    if (pushEnabled !== undefined) updateData.push_enabled = pushEnabled;
    if (emailEnabled !== undefined) updateData.email_enabled = emailEnabled;

    // Upsert (insert or update)
    const { data: settings, error } = await supabase
      .from('notification_settings')
      .upsert(updateData, { onConflict: 'user_id' })
      .select()
      .single();

    if (error) {
      console.error('Update notification settings error:', error);
      return res.status(500).json({ error: 'Failed to update notification settings' });
    }

    res.json({
      success: true,
      settings: {
        notifyNoActivity: settings.notify_no_activity,
        notifyUnusualPattern: settings.notify_unusual_pattern,
        notifySensorOffline: settings.notify_sensor_offline,
        notifyWeeklyReport: settings.notify_weekly_report,
        noActivityHours: settings.no_activity_hours,
        quietHoursEnabled: settings.quiet_hours_enabled,
        quietHoursStart: settings.quiet_hours_start,
        quietHoursEnd: settings.quiet_hours_end,
        pushEnabled: settings.push_enabled,
        emailEnabled: settings.email_enabled
      }
    });

  } catch (error) {
    console.error('Update notification settings error:', error);
    res.status(500).json({ error: error.message });
  }
});

module.exports = router;
