const express = require('express');
const router = express.Router();
const { getDb } = require('../database');
const { authenticate, requireAdmin } = require('../middleware/auth');
const { logAction } = require('../utils/audit');
const { sendApprovalNotification, sendSuspensionEmail } = require('../utils/email');

// All admin routes require authentication + admin role
router.use(authenticate, requireAdmin);

// GET /api/admin/users
router.get('/users', (req, res) => {
  const db = getDb();
  const { status, page = 1, limit = 50 } = req.query;
  const offset = (parseInt(page) - 1) * parseInt(limit);

  let query = 'SELECT id, full_name, email, department, role, status, created_at, last_login FROM users';
  const params = [];
  if (status) { query += ' WHERE status = ?'; params.push(status); }
  query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
  params.push(parseInt(limit), offset);

  const users = db.prepare(query).all(...params);
  const { total } = db.prepare('SELECT COUNT(*) as total FROM users' + (status ? ' WHERE status = ?' : '')).get(...(status ? [status] : []));

  res.json({ users, total });
});

// PUT /api/admin/users/:id/status
router.put('/users/:id/status', (req, res) => {
  const { status } = req.body;
  const validStatuses = ['active', 'pending', 'suspended'];
  if (!validStatuses.includes(status)) return res.status(400).json({ error: 'Invalid status' });

  const db = getDb();
  const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id);
  if (!user) return res.status(404).json({ error: 'User not found' });

  // Prevent admin from suspending themselves
  if (parseInt(req.params.id) === req.user.id)
    return res.status(400).json({ error: 'Cannot change your own account status' });

  const prevStatus = user.status;
  db.prepare('UPDATE users SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?').run(status, req.params.id);

  logAction(req.user.id, req.user.email, req.user.full_name, 'USER_STATUS_CHANGE',
    `Changed user ${user.email} status from ${prevStatus} to ${status}`, req);

  if (status === 'active' && prevStatus === 'pending') {
    sendApprovalNotification(user).catch(() => {});
  }
  if (status === 'suspended') {
    sendSuspensionEmail(user).catch(() => {});
  }

  res.json({ message: `User status updated to ${status}` });
});

// PUT /api/admin/users/:id/role
router.put('/users/:id/role', (req, res) => {
  const { role } = req.body;
  if (!['admin', 'staff'].includes(role)) return res.status(400).json({ error: 'Invalid role' });

  const db = getDb();
  const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id);
  if (!user) return res.status(404).json({ error: 'User not found' });

  db.prepare('UPDATE users SET role = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?').run(role, req.params.id);
  logAction(req.user.id, req.user.email, req.user.full_name, 'ROLE_CHANGE',
    `Changed ${user.email} role to ${role}`, req);

  res.json({ message: `User role updated to ${role}` });
});

// DELETE /api/admin/users/:id
router.delete('/users/:id', (req, res) => {
  if (parseInt(req.params.id) === req.user.id)
    return res.status(400).json({ error: 'Cannot delete your own account' });

  const db = getDb();
  const user = db.prepare('SELECT email, full_name FROM users WHERE id = ?').get(req.params.id);
  if (!user) return res.status(404).json({ error: 'User not found' });

  db.prepare('DELETE FROM users WHERE id = ?').run(req.params.id);
  logAction(req.user.id, req.user.email, req.user.full_name, 'DELETE_USER',
    `Deleted user ${user.email}`, req);

  res.json({ message: 'User deleted' });
});

// GET /api/admin/audit-logs
router.get('/audit-logs', (req, res) => {
  const db = getDb();
  const { page = 1, limit = 50, user_email, action } = req.query;
  const offset = (parseInt(page) - 1) * parseInt(limit);

  let where = [];
  const params = [];

  if (user_email) { where.push('user_email LIKE ?'); params.push(`%${user_email}%`); }
  if (action) { where.push('action = ?'); params.push(action); }

  const whereStr = where.length ? ' WHERE ' + where.join(' AND ') : '';
  const logs = db.prepare(`SELECT * FROM audit_logs${whereStr} ORDER BY timestamp DESC LIMIT ? OFFSET ?`)
    .all(...params, parseInt(limit), offset);
  const { total } = db.prepare(`SELECT COUNT(*) as total FROM audit_logs${whereStr}`).get(...params);

  res.json({ logs, total });
});

// GET /api/admin/stats
router.get('/stats', (req, res) => {
  const db = getDb();
  const today = new Date().toISOString().split('T')[0];
  const future = new Date(Date.now() + 30 * 24 * 3600000).toISOString().split('T')[0];

  const stats = {
    total_users: db.prepare('SELECT COUNT(*) as c FROM users').get().c,
    active_users: db.prepare("SELECT COUNT(*) as c FROM users WHERE status = 'active'").get().c,
    pending_users: db.prepare("SELECT COUNT(*) as c FROM users WHERE status = 'pending'").get().c,
    suspended_users: db.prepare("SELECT COUNT(*) as c FROM users WHERE status = 'suspended'").get().c,
    total_certs: db.prepare('SELECT COUNT(*) as c FROM certificates').get().c,
    expiring_certs: db.prepare(`SELECT COUNT(*) as c FROM certificates WHERE next_due_date BETWEEN ? AND ?`).get(today, future).c,
    recent_logins: db.prepare("SELECT COUNT(*) as c FROM audit_logs WHERE action = 'LOGIN' AND timestamp > datetime('now', '-7 days')").get().c
  };

  res.json({ stats });
});

// GET /api/admin/notifications/check — manual trigger
router.post('/notifications/check', async (req, res) => {
  const { checkExpiringCertificates } = require('../utils/scheduler');
  await checkExpiringCertificates();
  res.json({ message: 'Expiry check completed' });
});

module.exports = router;
