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

router.post('/login', async (req, res, next) => {
  try {
    const db = getDB();
    const { email, password } = req.body;
    if (!email || !password) return err(res, 'Email dan password wajib diisi');

    const [users] = await db.query('SELECT * FROM users WHERE email = ?', [email]);
    if (users.length === 0 || !bcrypt.compareSync(password, users[0].password)) {
      await logActivity('WARNING', `Login gagal: ${email}`, null, req.ip);
      return err(res, 'Email atau password salah', 401);
    }
    const user = users[0];
    if (user.status !== 'Aktif') return err(res, 'Akun Anda dinonaktifkan', 403);

    const token = jwt.sign({ id: user.id, email: user.email, nama: user.nama, role: user.role }, JWT_SECRET, { expiresIn: '8h' });
    await logActivity('INFO', `Login berhasil: ${email}`, user.id, req.ip);
    ok(res, { token, user: { id: user.id, nama: user.nama, email: user.email, role: user.role } }, 'Login berhasil');
  } catch (e) { next(e); }
});

router.post('/logout', auth(), async (req, res) => {
  await logActivity('INFO', `Logout: ${req.user.email}`, req.user.id, req.ip);
  ok(res, null, 'Logout berhasil');
});

router.get('/me', auth(), async (req, res, next) => {
  try {
    const db = getDB();
    const [users] = await db.query('SELECT id, nama, email, role, status, created_at FROM users WHERE id = ?', [req.user.id]);
    if (users.length === 0) return err(res, 'User not found', 404);
    ok(res, users[0]);
  } catch (e) { next(e); }
});

module.exports = router;
