const express = require('express');
const bcrypt = require('bcryptjs');
const router = express.Router();
const { getDB } = require('../config/database');
const { auth } = require('../middleware/auth');
const { ok, err, logActivity } = require('../helpers/response');

router.get('/', auth(['Admin']), async (req, res, next) => {
  try {
    const db = getDB();
    const [data] = await db.query('SELECT id, nama, email, role, status, created_at FROM users ORDER BY id');
    ok(res, { data, total: data.length });
  } catch (e) { next(e); }
});

router.get('/ustadz', async (req, res, next) => {
  try {
    const db = getDB();
    const [data] = await db.query(`
      SELECT id, nama, role, last_active,
        (last_active >= DATE_SUB(NOW(), INTERVAL 5 MINUTE)) as is_online
      FROM users WHERE (role = 'Ustadz' OR role = 'Admin') AND status = 'Aktif'
    `);
    ok(res, { data });
  } catch (e) { next(e); }
});

router.post('/', auth(['Admin']), async (req, res, next) => {
  try {
    const db = getDB();
    const { nama, email, password, role, status } = req.body;
    if (!nama || !email || !password) return err(res, 'Nama, email, dan password wajib diisi');
    const [existing] = await db.query('SELECT id FROM users WHERE email = ?', [email]);
    if (existing.length > 0) return err(res, 'Email sudah digunakan');
    const hash = bcrypt.hashSync(password, 10);
    const [result] = await db.query('INSERT INTO users (nama, email, password, role, status) VALUES (?,?,?,?,?)', [nama, email, hash, role || 'Editor', status || 'Aktif']);
    await logActivity('SUCCESS', `User ditambahkan: ${email}`, req.user.id, req.ip);
    ok(res, { id: result.insertId }, 'Pengguna berhasil ditambahkan');
  } catch (e) { next(e); }
});

router.put('/:id', auth(['Admin']), async (req, res, next) => {
  try {
    const db = getDB();
    const [eRows] = await db.query('SELECT * FROM users WHERE id = ?', [req.params.id]);
    if (eRows.length === 0) return err(res, 'Pengguna tidak ditemukan', 404);
    const e = eRows[0];
    const { nama, email, password, role, status } = req.body;
    const newHash = password ? bcrypt.hashSync(password, 10) : e.password;
    await db.query(
      'UPDATE users SET nama=?,email=?,password=?,role=?,status=? WHERE id=?',
      [nama || e.nama, email || e.email, newHash, role || e.role, status || e.status, req.params.id]
    );
    ok(res, null, 'Pengguna berhasil diperbarui');
  } catch (e) { next(e); }
});

router.delete('/:id', auth(['Admin']), async (req, res, next) => {
  try {
    const db = getDB();
    if (+req.params.id === req.user.id) return err(res, 'Tidak dapat menghapus akun sendiri');
    await db.query('DELETE FROM users WHERE id = ?', [req.params.id]);
    ok(res, null, 'Pengguna dihapus');
  } catch (e) { next(e); }
});

router.post('/heartbeat', auth(), async (req, res, next) => {
  try {
    const db = getDB();
    await db.query('UPDATE users SET last_active = NOW() WHERE id = ?', [req.user.id]);
    ok(res, null, 'OK');
  } catch (e) { next(e); }
});

module.exports = router;
