import { Router } from 'express';
import { getDb } from '../config/database.js';
import { authenticateToken } from '../middleware/auth.js';

const router = Router();

// GET /api/notifications — List recent notifications for the current user
router.get('/', authenticateToken, async (req, res) => {
  try {
    const db = getDb();
    const notifications = await db.all(
      `SELECT * FROM notifications WHERE user_id = ? ORDER BY created_at DESC LIMIT 50`,
      [req.user.id],
    );
    const unreadCount = notifications.filter(n => !n.read).length;
    res.json({ notifications, unreadCount });
  } catch {
    res.status(500).json({ error: 'Failed to load notifications' });
  }
});

// POST /api/notifications/read-all — Mark all notifications as read
// NOTE: Must be declared before /:id/read to avoid routing collision
router.post('/read-all', authenticateToken, async (req, res) => {
  try {
    const db = getDb();
    await db.run('UPDATE notifications SET read = 1 WHERE user_id = ?', [req.user.id]);
    res.json({ success: true });
  } catch {
    res.status(500).json({ error: 'Failed to update notifications' });
  }
});

// POST /api/notifications/:id/read — Mark a single notification as read
router.post('/:id/read', authenticateToken, async (req, res) => {
  try {
    const db = getDb();
    await db.run(
      'UPDATE notifications SET read = 1 WHERE id = ? AND user_id = ?',
      [req.params.id, req.user.id],
    );
    res.json({ success: true });
  } catch {
    res.status(500).json({ error: 'Failed to update notification' });
  }
});

// DELETE /api/notifications/all — Delete all notifications for current user
// NOTE: Declared before /:id to avoid routing collision
router.delete('/all', authenticateToken, async (req, res) => {
  try {
    const db = getDb();
    await db.run('DELETE FROM notifications WHERE user_id = ?', [req.user.id]);
    res.json({ success: true });
  } catch {
    res.status(500).json({ error: 'Failed to delete notifications' });
  }
});

// DELETE /api/notifications/:id — Delete a single notification
router.delete('/:id', authenticateToken, async (req, res) => {
  try {
    const db = getDb();
    await db.run(
      'DELETE FROM notifications WHERE id = ? AND user_id = ?',
      [req.params.id, req.user.id],
    );
    res.json({ success: true });
  } catch {
    res.status(500).json({ error: 'Failed to delete notification' });
  }
});

export default router;
