const express = require('express');
const router = express.Router();
const { getDB } = require('../config/database');
const { upload } = require('../config/multer');
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 = '', jenis = '', status = '', kategori = '' } = 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 kategori LIKE ?)'; params.push(`%${search}%`, `%${search}%`); }
    if (jenis) { where += ' AND jenis = ?'; params.push(jenis); }
    if (status) { where += ' AND status = ?'; params.push(status); }
    if (kategori) { where += ' AND kategori = ?'; params.push(kategori); }
    const result = await paginate(`SELECT * FROM materi ${where} ORDER BY created_at DESC`, params, +page, +limit);
    ok(res, result);
  } catch (e) { next(e); }
});

router.get('/stats', auth(), async (req, res, next) => {
  try {
    const db = getDB();
    const [totalR] = await db.query('SELECT COUNT(*) as c FROM materi');
    const [tulisanR] = await db.query('SELECT COUNT(*) as c FROM materi WHERE jenis = ?', ['Tulisan']);
    const [videoR] = await db.query('SELECT COUNT(*) as c FROM materi WHERE jenis = ?', ['Video']);
    const [audioR] = await db.query('SELECT COUNT(*) as c FROM materi WHERE jenis = ?', ['Audio']);
    const [publishedR] = await db.query('SELECT COUNT(*) as c FROM materi WHERE status = ?', ['Publikasi']);
    ok(res, { total: totalR[0].c, tulisan: tulisanR[0].c, video: videoR[0].c, audio: audioR[0].c, published: publishedR[0].c });
  } catch (e) { next(e); }
});

router.post('/', auth(['Admin', 'Editor', 'Ustadz']), upload.single('gambar'), async (req, res, next) => {
  try {
    const db = getDB();
    const { judul, jenis, kategori, status, excerpt, konten, url, durasi } = req.body;
    if (!judul) return err(res, 'Judul materi wajib diisi');
    const gambar = req.file ? `/uploads/${req.file.filename}` : req.body.gambar || '';
    const [result] = await db.query(
      'INSERT INTO materi (judul, jenis, kategori, status, excerpt, konten, url, durasi, gambar, penulis_id) VALUES (?,?,?,?,?,?,?,?,?,?)',
      [judul, jenis || 'Tulisan', kategori || 'Umum', status || 'Draft', excerpt || '', konten || '', url || '', durasi || '', gambar, req.user.id]
    );
    await logActivity('SUCCESS', `Materi ditambahkan: ${judul}`, req.user.id, req.ip);
    const [item] = await db.query('SELECT * FROM materi WHERE id = ?', [result.insertId]);
    if ((status || 'Draft') === 'Publikasi' || (status || 'Draft') === 'Terbit') notifySubscribers(db, 'materi', judul, excerpt || '');
    ok(res, item[0], 'Materi berhasil ditambahkan');
  } catch (e) { next(e); }
});

router.put('/:id', auth(['Admin', 'Editor', 'Ustadz']), upload.single('gambar'), async (req, res, next) => {
  try {
    const db = getDB();
    const { id } = req.params;
    const [existingRows] = await db.query('SELECT * FROM materi WHERE id = ?', [id]);
    if (existingRows.length === 0) return err(res, 'Materi tidak ditemukan', 404);
    const existing = existingRows[0];
    const { judul, jenis, kategori, status, excerpt, konten, url, durasi } = req.body;
    const gambar = req.file ? `/uploads/${req.file.filename}` : req.body.gambar || existing.gambar;
    await db.query(
      'UPDATE materi SET judul=?,jenis=?,kategori=?,status=?,excerpt=?,konten=?,url=?,durasi=?,gambar=? WHERE id=?',
      [judul || existing.judul, jenis || existing.jenis, kategori || existing.kategori, status || existing.status, excerpt || existing.excerpt, konten || existing.konten, url || existing.url, durasi || existing.durasi, gambar, id]
    );
    await logActivity('SUCCESS', `Materi diperbarui: ${judul || existing.judul}`, req.user.id, req.ip);
    const [item] = await db.query('SELECT * FROM materi WHERE id = ?', [id]);
    ok(res, item[0], 'Materi berhasil diperbarui');
  } catch (e) { next(e); }
});

router.delete('/:id', auth(['Admin', 'Editor']), async (req, res, next) => {
  try {
    const db = getDB();
    const { id } = req.params;
    const [existingRows] = await db.query('SELECT * FROM materi WHERE id = ?', [id]);
    if (existingRows.length === 0) return err(res, 'Materi tidak ditemukan', 404);
    await db.query('DELETE FROM materi WHERE id = ?', [id]);
    await logActivity('WARNING', `Materi dihapus: ${existingRows[0].judul}`, req.user.id, req.ip);
    ok(res, null, 'Materi 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 materi WHERE id IN (?)', [ids]);
    await logActivity('WARNING', `Bulk delete materi: ${ids.length} item`, req.user.id, req.ip);
    ok(res, null, `${ids.length} materi berhasil dihapus`);
  } catch (e) { next(e); }
});

module.exports = router;
