const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const { getDb } = require('../database');
const { authenticate } = require('../middleware/auth');
const { logAction } = require('../utils/audit');

// GET /api/users/profile
router.get('/profile', authenticate, (req, res) => {
  const db = getDb();
  const user = db.prepare('SELECT id, full_name, email, department, role, status, created_at, last_login FROM users WHERE id = ?').get(req.user.id);
  res.json({ user });
});

// PUT /api/users/profile
router.put('/profile', authenticate, (req, res) => {
  const { full_name, department } = req.body;
  if (!full_name || !department) return res.status(400).json({ error: 'Name and department required' });

  const db = getDb();
  db.prepare('UPDATE users SET full_name = ?, department = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?')
    .run(full_name.trim(), department.trim(), req.user.id);

  logAction(req.user.id, req.user.email, req.user.full_name, 'PROFILE_UPDATE', 'Updated profile', req);
  res.json({ message: 'Profile updated successfully' });
});

// PUT /api/users/change-password
router.put('/change-password', authenticate, (req, res) => {
  const { current_password, new_password } = req.body;
  if (!current_password || !new_password) return res.status(400).json({ error: 'Both passwords required' });
  if (new_password.length < 6) return res.status(400).json({ error: 'New password must be at least 6 characters' });

  const db = getDb();
  const user = db.prepare('SELECT password_hash FROM users WHERE id = ?').get(req.user.id);
  if (!bcrypt.compareSync(current_password, user.password_hash))
    return res.status(400).json({ error: 'Current password is incorrect' });

  const hash = bcrypt.hashSync(new_password, 10);
  db.prepare('UPDATE users SET password_hash = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?').run(hash, req.user.id);

  logAction(req.user.id, req.user.email, req.user.full_name, 'PASSWORD_CHANGE', 'Changed password', req);
  res.json({ message: 'Password changed successfully' });
});

// GET /api/users/notifications
router.get('/notifications', authenticate, (req, res) => {
  const db = getDb();
  const notifs = db.prepare(`
    SELECT n.*, c.certificate_number, c.client, c.next_due_date
    FROM notifications n
    LEFT JOIN certificates c ON n.certificate_id = c.id
    WHERE n.user_id = ?
    ORDER BY n.created_at DESC
    LIMIT 50
  `).all(req.user.id);
  const unread = db.prepare('SELECT COUNT(*) as c FROM notifications WHERE user_id = ? AND read = 0').get(req.user.id).c;
  res.json({ notifications: notifs, unread });
});

// PUT /api/users/notifications/read
router.put('/notifications/read', authenticate, (req, res) => {
  const db = getDb();
  db.prepare('UPDATE notifications SET read = 1 WHERE user_id = ?').run(req.user.id);
  res.json({ message: 'All notifications marked as read' });
});

// PUT /api/users/notifications/:id/read
router.put('/notifications/:id/read', authenticate, (req, res) => {
  const db = getDb();
  db.prepare('UPDATE notifications SET read = 1 WHERE id = ? AND user_id = ?').run(req.params.id, req.user.id);
  res.json({ message: 'Notification marked as read' });
});

module.exports = router;
