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

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

// Preview undangan oleh wali kelas / admin
router.get('/preview/santri/:id', async (req, res) => {
  const id = Number(req.params.id);
  const [s] = await db.select().from(santri).where(eq(santri.id, id)).limit(1);
  if (!s) return res.status(404).render('error', { title: 'Not Found', message: 'Santri tidak ditemukan.' });

  if (req.user.role !== 'admin') {
    const [k] = await db.select().from(kelas).where(eq(kelas.id, s.kelasId)).limit(1);
    if (!k || k.waliKelasUserId !== req.user.id) {
      return res.status(403).render('error', { title: 'Forbidden', message: 'Akses ditolak.' });
    }
  }

  const [a] = await db.select().from(angkatan).where(eq(angkatan.id, s.angkatanId)).limit(1);
  const baseUrl = `${req.protocol}://${req.get('host')}`;
  res.render('public/undangan', {
    title: `Preview - ${s.nama}`,
    santriItem: s,
    angkatanItem: a,
    baseUrl,
    isPreview: true,
    layout: false,
  });
});

// Preview by angkatan (dummy nama "Ananda/Aninda")
router.get('/preview/angkatan/:id', async (req, res) => {
  const id = Number(req.params.id);
  const [a] = await db.select().from(angkatan).where(eq(angkatan.id, id)).limit(1);
  if (!a) return res.status(404).render('error', { title: 'Not Found', message: 'Angkatan tidak ditemukan.' });
  const baseUrl = `${req.protocol}://${req.get('host')}`;
  res.render('public/undangan', {
    title: `Preview Angkatan ${a.nomor}`,
    santriItem: { nama: 'Ananda Wali Santri NFBS Bogor', nis: '-', slug: '-' },
    angkatanItem: a,
    baseUrl,
    isPreview: true,
    layout: false,
  });
});

export default router;
