const express = require('express');
const router = express.Router();
const { getDB } = require('../config/database');
const { notifySubscribers } = require('../config/smtp');
const { auth } = require('../middleware/auth');
const { ok, err, logActivity, paginate } = require('../helpers/response');

router.get('/', async (req, res, next) => {
  try {
    const db = getDB();
    const { page = 1, limit = 10, search = '', status = '' } = req.query;
    const isPublic = !req.headers.authorization;
    let where = 'WHERE 1=1'; const params = [];
    if (isPublic && !status) { where += ' AND status = ?'; params.push('Publikasi'); }
    if (search) { where += ' AND (judul LIKE ? OR khatib LIKE ?)'; params.push(`%${search}%`, `%${search}%`); }
    if (status) { where += ' AND status = ?'; params.push(status); }
    const result = await paginate(`SELECT * FROM risalah ${where} ORDER BY tanggal DESC`, params, +page, +limit);
    ok(res, result);
  } catch (e) { next(e); }
});

router.post('/', auth(['Admin', 'Editor', 'Ustadz']), async (req, res, next) => {
  try {
    const db = getDB();
    const { judul, khatib, tanggal, excerpt, konten, pdf_url, status } = req.body;
    if (!judul) return err(res, 'Judul khutbah wajib diisi');
    const [result] = await db.query(
      'INSERT INTO risalah (judul, khatib, tanggal, excerpt, konten, pdf_url, status) VALUES (?,?,?,?,?,?,?)',
      [judul, khatib || '', tanggal || null, excerpt || '', konten || '', pdf_url || '', status || 'Draft']
    );
    await logActivity('SUCCESS', `Risalah ditambahkan: ${judul}`, req.user.id, req.ip);
    const [item] = await db.query('SELECT * FROM risalah WHERE id = ?', [result.insertId]);
    if ((status || 'Draft') === 'Publikasi' || (status || 'Draft') === 'Terbit') notifySubscribers(db, 'risalah', judul, khatib ? `Khatib: ${khatib}` : '');
    ok(res, item[0]);
  } catch (e) { next(e); }
});

router.put('/:id', auth(['Admin', 'Editor', 'Ustadz']), async (req, res, next) => {
  try {
    const db = getDB();
    const { id } = req.params;
    const { judul, khatib, tanggal, excerpt, konten, pdf_url, status } = req.body;
    const [eRows] = await db.query('SELECT * FROM risalah WHERE id = ?', [id]);
    if (eRows.length === 0) return err(res, 'Risalah tidak ditemukan', 404);
    const existing = eRows[0];
    await db.query(
      'UPDATE risalah SET judul=?,khatib=?,tanggal=?,excerpt=?,konten=?,pdf_url=?,status=? WHERE id=?',
      [judul || existing.judul, khatib || existing.khatib, tanggal || existing.tanggal, excerpt || existing.excerpt, konten || existing.konten, pdf_url || existing.pdf_url, status || existing.status, id]
    );
    const [item] = await db.query('SELECT * FROM risalah WHERE id = ?', [id]);
    ok(res, item[0]);
  } catch (e) { next(e); }
});

router.delete('/:id', auth(['Admin', 'Editor']), async (req, res, next) => {
  try {
    const db = getDB();
    const [eRows] = await db.query('SELECT id FROM risalah WHERE id = ?', [req.params.id]);
    if (eRows.length === 0) return err(res, 'Risalah tidak ditemukan', 404);
    await db.query('DELETE FROM risalah WHERE id = ?', [req.params.id]);
    ok(res, null, 'Risalah berhasil dihapus');
  } catch (e) { next(e); }
});

router.post('/bulk-delete', auth(['Admin', 'Editor']), async (req, res, next) => {
  try {
    const db = getDB();
    const { ids } = req.body;
    if (!Array.isArray(ids) || ids.length === 0) return err(res, 'Tidak ada ID yang dipilih');
    await db.query('DELETE FROM risalah WHERE id IN (?)', [ids]);
    ok(res, null, `${ids.length} risalah berhasil dihapus`);
  } catch (e) { next(e); }
});

module.exports = router;
