const express = require('express');
const router = express.Router();
const db = require('../db');

// Require Auth
router.use((req, res, next) => {
  if (!req.session.user_id) return res.status(401).json({ error: 'Unauthorized' });
  next();
});

router.get('/', async (req, res) => {
  try {
    const user = await db.fetch('SELECT id, full_name, email, role FROM users WHERE id = ?', [req.session.user_id]);
    res.json(user || {});
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

router.put('/', async (req, res) => {
  const { full_name, email, role } = req.body;
  try {
    await db.query('UPDATE users SET full_name = ?, email = ?, role = ? WHERE id = ?', [full_name, email, role, req.session.user_id]);
    req.session.full_name = full_name;
    req.session.email = email;
    req.session.role = role;
    res.json({ success: true });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

module.exports = router;
