import { Router } from 'express';
import { db } from '../db/index.js';
import { angkatan, kelas, santri } from '../db/schema.js';
import { eq, sql, and } from 'drizzle-orm';
import { requireAuth } from '../middleware/auth.js';

const router = Router();

router.use(requireAuth);

router.get('/', async (req, res) => {
  if (req.user.role === 'admin') {
    // Admin: ringkasan semua angkatan + counter
    const angkatanList = await db.select().from(angkatan).orderBy(angkatan.nomor);

    const stats = await Promise.all(
      angkatanList.map(async (a) => {
        const [row] = await db
          .select({
            total: sql`COUNT(*)`.mapWith(Number),
            terkirim: sql`SUM(CASE WHEN ${santri.statusTerkirim} = TRUE THEN 1 ELSE 0 END)`.mapWith(Number),
          })
          .from(santri)
          .where(eq(santri.angkatanId, a.id));
        return { ...a, total: row?.total || 0, terkirim: row?.terkirim || 0 };
      }),
    );

    return res.render('dashboard/admin', {
      title: 'Dashboard Admin',
      angkatanStats: stats,
    });
  }

  // Wali kelas: lihat kelas yang dipegang
  const kelasRows = await db
    .select()
    .from(kelas)
    .where(eq(kelas.waliKelasUserId, req.user.id));

  const kelasStats = await Promise.all(
    kelasRows.map(async (k) => {
      const [row] = await db
        .select({
          total: sql`COUNT(*)`.mapWith(Number),
          terkirim: sql`SUM(CASE WHEN ${santri.statusTerkirim} = TRUE THEN 1 ELSE 0 END)`.mapWith(Number),
        })
        .from(santri)
        .where(eq(santri.kelasId, k.id));
      const [angkatanRow] = await db.select().from(angkatan).where(eq(angkatan.id, k.angkatanId)).limit(1);
      return { ...k, angkatanNomor: angkatanRow?.nomor, total: row?.total || 0, terkirim: row?.terkirim || 0 };
    }),
  );

  res.render('dashboard/wali', { title: 'Dashboard Wali Kelas', kelasStats });
});

export default router;
