import { db } from '../db/index.js';
import { kelas } from '../db/schema.js';
import { eq } from 'drizzle-orm';

export function requireAuth(req, res, next) {
  if (!req.isAuthenticated || !req.isAuthenticated()) {
    req.flash('error', 'Silakan login terlebih dahulu.');
    return res.redirect('/login');
  }
  next();
}

export function requireAdmin(req, res, next) {
  if (!req.user || req.user.role !== 'admin') {
    return res.status(403).render('error', { title: 'Forbidden', message: 'Akses hanya untuk admin.' });
  }
  next();
}

/**
 * Pastikan wali kelas hanya akses kelasnya sendiri.
 * Admin bypass.
 */
export async function ensureClassAccess(req, res, next) {
  if (!req.user) return res.status(401).end();
  if (req.user.role === 'admin') return next();

  const kelasId = Number(req.params.kelasId || req.body.kelasId || req.query.kelasId);
  if (!kelasId) return res.status(400).render('error', { title: 'Bad Request', message: 'Kelas ID tidak valid.' });

  const rows = await db.select().from(kelas).where(eq(kelas.id, kelasId)).limit(1);
  if (rows.length === 0 || rows[0].waliKelasUserId !== req.user.id) {
    return res.status(403).render('error', { title: 'Forbidden', message: 'Anda tidak memiliki akses ke kelas ini.' });
  }
  req.kelasContext = rows[0];
  next();
}
