import { Router } from 'express';
import bcrypt from 'bcryptjs';
import { db } from '../db/index.js';
import { users } from '../db/schema.js';
import { eq, asc } from 'drizzle-orm';
import { requireAuth, requireAdmin } from '../middleware/auth.js';
import { logAudit } from '../lib/audit.js';

const router = Router();
router.use(requireAuth, requireAdmin);

router.get('/', async (req, res) => {
  const list = await db.select().from(users).orderBy(asc(users.nama));
  list.forEach((u) => delete u.passwordHash);
  res.render('users/index', { title: 'Manajemen User', userList: list });
});

router.get('/new', (req, res) => {
  res.render('users/form', { title: 'Tambah User', item: null });
});

router.post('/', async (req, res) => {
  const { nama, email, password, role } = req.body;
  const emailLower = String(email || '').toLowerCase().trim();
  const exist = await db.select().from(users).where(eq(users.email, emailLower)).limit(1);
  if (exist.length > 0) {
    req.flash('error', 'Email sudah terdaftar.');
    return res.redirect('/users/new');
  }
  const passwordHash = password ? await bcrypt.hash(password, 10) : null;
  await db.insert(users).values({ nama, email: emailLower, passwordHash, role: role || 'wali_kelas' });
  await logAudit({ userId: req.user.id, action: 'user.create', entityType: 'user', metadata: { email: emailLower, role } });
  req.flash('success', `User ${nama} dibuat.`);
  res.redirect('/users');
});

router.get('/:id/edit', async (req, res) => {
  const id = Number(req.params.id);
  const [item] = await db.select().from(users).where(eq(users.id, id)).limit(1);
  if (!item) return res.status(404).render('error', { title: 'Not Found', message: 'User tidak ditemukan.' });
  delete item.passwordHash;
  res.render('users/form', { title: 'Edit User', item });
});

router.put('/:id', async (req, res) => {
  const id = Number(req.params.id);
  const { nama, email, password, role } = req.body;
  const update = { nama, email: String(email).toLowerCase().trim(), role };
  if (password && password.length >= 6) {
    update.passwordHash = await bcrypt.hash(password, 10);
  }
  await db.update(users).set(update).where(eq(users.id, id));
  await logAudit({ userId: req.user.id, action: 'user.update', entityType: 'user', entityId: id });
  req.flash('success', 'User diperbarui.');
  res.redirect('/users');
});

router.delete('/:id', async (req, res) => {
  const id = Number(req.params.id);
  if (id === req.user.id) {
    req.flash('error', 'Tidak bisa menghapus akun sendiri.');
    return res.redirect('/users');
  }
  await db.delete(users).where(eq(users.id, id));
  await logAudit({ userId: req.user.id, action: 'user.delete', entityType: 'user', entityId: id });
  req.flash('success', 'User dihapus.');
  res.redirect('/users');
});

export default router;
