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

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

async function loadSantriContext(req, santriId) {
  const [s] = await db.select().from(santri).where(eq(santri.id, santriId)).limit(1);
  if (!s) return null;
  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 'forbidden';
  }
  const [k] = await db.select().from(kelas).where(eq(kelas.id, s.kelasId)).limit(1);
  const [a] = await db.select().from(angkatan).where(eq(angkatan.id, s.angkatanId)).limit(1);
  return { s, k, a };
}

function buildContext(s, k, a, baseUrl) {
  const link = `${baseUrl}/${a.nomor}/${s.slug}`;
  const text = renderTemplate(a.waTemplate || '', {
    nama: s.nama,
    nis: s.nis,
    kelas: k.nama,
    link,
  });
  const url = buildWaUrl(decrypt(s.nomorWaEnc), text);
  return { link, text, url };
}

// Konfirmasi popup → return URL untuk dibuka di tab/WA
router.post('/santri/:id', async (req, res) => {
  const id = Number(req.params.id);
  const ctx = await loadSantriContext(req, id);
  if (!ctx) return res.status(404).json({ error: 'Santri tidak ditemukan.' });
  if (ctx === 'forbidden') return res.status(403).json({ error: 'Forbidden' });

  const baseUrl = `${req.protocol}://${req.get('host')}`;
  const { url } = buildContext(ctx.s, ctx.k, ctx.a, baseUrl);

  // Auto-mark terkirim
  await db
    .update(santri)
    .set({
      statusTerkirim: true,
      terkirimAt: new Date(),
      terkirimByUserId: req.user.id,
    })
    .where(eq(santri.id, id));

  await logAudit({
    userId: req.user.id,
    action: 'undangan.send',
    entityType: 'santri',
    entityId: id,
    metadata: { kelasId: ctx.k.id },
  });

  res.json({ ok: true, waUrl: url });
});

// Resend (tidak ubah status)
router.post('/resend/:id', async (req, res) => {
  const id = Number(req.params.id);
  const ctx = await loadSantriContext(req, id);
  if (!ctx) return res.status(404).json({ error: 'Santri tidak ditemukan.' });
  if (ctx === 'forbidden') return res.status(403).json({ error: 'Forbidden' });

  const baseUrl = `${req.protocol}://${req.get('host')}`;
  const { url } = buildContext(ctx.s, ctx.k, ctx.a, baseUrl);

  await logAudit({
    userId: req.user.id,
    action: 'undangan.resend',
    entityType: 'santri',
    entityId: id,
  });

  res.json({ ok: true, waUrl: url });
});

// Reset/undo terkirim
router.post('/reset/:id', async (req, res) => {
  const id = Number(req.params.id);
  const ctx = await loadSantriContext(req, id);
  if (!ctx) return res.status(404).json({ error: 'Santri tidak ditemukan.' });
  if (ctx === 'forbidden') return res.status(403).json({ error: 'Forbidden' });

  await db
    .update(santri)
    .set({ statusTerkirim: false, terkirimAt: null, terkirimByUserId: null })
    .where(eq(santri.id, id));

  await logAudit({
    userId: req.user.id,
    action: 'undangan.reset',
    entityType: 'santri',
    entityId: id,
  });

  res.json({ ok: true });
});

// Test send: ke nomor user sendiri
router.post('/test/:id', async (req, res) => {
  const id = Number(req.params.id);
  const ctx = await loadSantriContext(req, id);
  if (!ctx) return res.status(404).json({ error: 'Santri tidak ditemukan.' });
  if (ctx === 'forbidden') return res.status(403).json({ error: 'Forbidden' });

  const testNumber = String(req.body.nomor || '').trim();
  if (!testNumber) return res.status(400).json({ error: 'Nomor test wajib diisi.' });

  const baseUrl = `${req.protocol}://${req.get('host')}`;
  const { text, link } = buildContext(ctx.s, ctx.k, ctx.a, baseUrl);
  const url = buildWaUrl(testNumber, `[TEST UNDANGAN]\n\n${text}\n\nLink preview: ${link}`);

  await logAudit({
    userId: req.user.id,
    action: 'undangan.test_send',
    entityType: 'santri',
    entityId: id,
  });

  res.json({ ok: true, waUrl: url });
});

export default router;
