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, paginate } = require('../helpers/response');

router.get('/', async (req, res, next) => {
  try {
    const db = getDB();
    const { page = 1, limit = 10, search = '', 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 ?'; params.push(`%${search}%`); }
    if (status) { where += ' AND status = ?'; params.push(status); }
    if (kategori) { where += ' AND kategori = ?'; params.push(kategori); }
    const result = await paginate(`SELECT * FROM berita ${where} ORDER BY created_at DESC`, params, +page, +limit);
    ok(res, result);
  } catch (e) { next(e); }
});

router.post('/', auth(['Admin', 'Editor']), upload.single('gambar'), async (req, res, next) => {
  try {
    const db = getDB();
    const { judul, penulis, kategori, konten, status } = req.body;
    if (!judul) return err(res, 'Judul artikel wajib diisi');
    const gambar = req.file ? `/uploads/${req.file.filename}` : req.body.gambar || '';
    const [result] = await db.query(
      'INSERT INTO berita (judul, penulis, kategori, konten, gambar, status) VALUES (?,?,?,?,?,?)',
      [judul, penulis || 'Admin', kategori || 'Umum', konten || '', gambar, status || 'Draft']
    );
    const [item] = await db.query('SELECT * FROM berita WHERE id = ?', [result.insertId]);
    if ((status || 'Draft') === 'Publikasi' || (status || 'Draft') === 'Terbit') notifySubscribers(db, 'berita', judul, kategori ? `Kategori: ${kategori}` : '');
    ok(res, item[0]);
  } catch (e) { next(e); }
});

router.put('/:id', auth(['Admin', 'Editor']), upload.single('gambar'), async (req, res, next) => {
  try {
    const db = getDB();
    const [eRows] = await db.query('SELECT * FROM berita WHERE id = ?', [req.params.id]);
    if (eRows.length === 0) return err(res, 'Artikel tidak ditemukan', 404);
    const existing = eRows[0];
    const { judul, penulis, kategori, konten, status } = req.body;
    const gambar = req.file ? `/uploads/${req.file.filename}` : req.body.gambar || existing.gambar;
    await db.query(
      'UPDATE berita SET judul=?,penulis=?,kategori=?,konten=?,gambar=?,status=? WHERE id=?',
      [judul || existing.judul, penulis || existing.penulis, kategori || existing.kategori, konten || existing.konten, gambar, status || existing.status, req.params.id]
    );
    const [item] = await db.query('SELECT * FROM berita WHERE id = ?', [req.params.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 berita WHERE id = ?', [req.params.id]);
    if (eRows.length === 0) return err(res, 'Tidak ditemukan', 404);
    await db.query('DELETE FROM berita WHERE id = ?', [req.params.id]);
    ok(res, null, '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 berita WHERE id IN (?)', [ids]);
    ok(res, null, `${ids.length} artikel berhasil dihapus`);
  } catch (e) { next(e); }
});

module.exports = router;
