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);

/**
 * POST /api/push-tokens
 * Registers a push token for the current user
 */
router.post('/', async (req, res) => {
  try {
    const userId = req.user.userId;
    const { token, platform, deviceName } = req.body;

    if (!token) {
      return res.status(400).json({ error: 'Token is required' });
    }

    if (platform && !['ios', 'android', 'web'].includes(platform)) {
      return res.status(400).json({ error: 'Invalid platform. Must be: ios, android, or web' });
    }

    // Check if token already exists
    const { data: existing } = await supabase
      .from('push_tokens')
      .select('id, user_id')
      .eq('token', token)
      .single();

    if (existing) {
      // Update existing token (might have changed user)
      const { error: updateError } = await supabase
        .from('push_tokens')
        .update({
          user_id: userId,
          platform: platform || existing.platform,
          device_name: deviceName || existing.device_name,
          is_active: true,
          last_used_at: new Date().toISOString(),
          updated_at: new Date().toISOString()
        })
        .eq('id', existing.id);

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

      return res.json({
        success: true,
        message: 'Push token updated'
      });
    }

    // Create new token
    const { error: createError } = await supabase
      .from('push_tokens')
      .insert({
        user_id: userId,
        token,
        platform: platform || null,
        device_name: deviceName || null,
        is_active: true,
        last_used_at: new Date().toISOString()
      });

    if (createError) {
      console.error('Create push token error:', createError);
      return res.status(500).json({ error: 'Failed to register push token' });
    }

    res.json({
      success: true,
      message: 'Push token registered'
    });

  } catch (error) {
    console.error('Register push token error:', error);
    res.status(500).json({ error: error.message });
  }
});

/**
 * DELETE /api/push-tokens
 * Removes a push token (logout or app uninstall)
 */
router.delete('/', async (req, res) => {
  try {
    const userId = req.user.userId;
    const { token } = req.body;

    if (!token) {
      return res.status(400).json({ error: 'Token is required' });
    }

    // Deactivate token (don't delete to keep history)
    const { error } = await supabase
      .from('push_tokens')
      .update({
        is_active: false,
        updated_at: new Date().toISOString()
      })
      .eq('token', token)
      .eq('user_id', userId);

    if (error) {
      console.error('Delete push token error:', error);
      return res.status(500).json({ error: 'Failed to remove push token' });
    }

    res.json({ success: true });

  } catch (error) {
    console.error('Delete push token error:', error);
    res.status(500).json({ error: error.message });
  }
});

module.exports = router;
