const express = require('express');
const path = require('path');
const fs = require('fs');
const router = express.Router();
const { getDB } = require('../config/database');
const { galeriUpload, compressImage } = require('../config/multer');
const { auth } = require('../middleware/auth');
const { ok, err, logActivity } = require('../helpers/response');

router.get('/', async (req, res, next) => {
  try {
    const db = getDB();
    const isPublic = !req.headers.authorization;
    let query = 'SELECT * FROM galeri';
    if (isPublic) query += " WHERE status = 'Publikasi'";
    query += ' ORDER BY created_at DESC';
    const [data] = await db.query(query);
    ok(res, { data, total: data.length });
  } catch (e) { next(e); }
});

router.post('/', auth(['Admin', 'Editor']), galeriUpload.single('foto'), async (req, res, next) => {
  try {
    const db = getDB();
    const { judul, album, status } = req.body;
    if (!judul) return err(res, 'Judul foto wajib diisi');
    if (!req.file) return err(res, 'File foto wajib diupload');
    const { url } = await compressImage(req.file.buffer, req.file.originalname);
    const [result] = await db.query(
      'INSERT INTO galeri (judul, album, url, status) VALUES (?,?,?,?)',
      [judul, album || 'Umum', url, status || 'Draft']
    );
    await logActivity('SUCCESS', `Foto galeri ditambahkan: ${judul}`, req.user.id, req.ip);
    const [item] = await db.query('SELECT * FROM galeri WHERE id = ?', [result.insertId]);
    ok(res, item[0], 'Foto berhasil diupload');
  } catch (e) { next(e); }
});

// PATCH — quick status toggle (JSON body, no file)
router.patch('/:id', auth(['Admin', 'Editor']), async (req, res, next) => {
  try {
    const db = getDB();
    const [eRows] = await db.query('SELECT * FROM galeri WHERE id = ?', [req.params.id]);
    if (eRows.length === 0) return err(res, 'Foto tidak ditemukan', 404);
    const existing = eRows[0];
    const { judul, album, status } = req.body;
    await db.query(
      'UPDATE galeri SET judul=?, album=?, status=? WHERE id=?',
      [judul || existing.judul, album || existing.album, status || existing.status, req.params.id]
    );
    const [item] = await db.query('SELECT * FROM galeri WHERE id = ?', [req.params.id]);
    ok(res, item[0], 'Status diperbarui');
  } catch (e) { next(e); }
});

// PUT — full edit with optional file upload (multipart/form-data)
router.put('/:id', auth(['Admin', 'Editor']), galeriUpload.single('foto'), async (req, res, next) => {
  try {
    const db = getDB();
    const [eRows] = await db.query('SELECT * FROM galeri WHERE id = ?', [req.params.id]);
    if (eRows.length === 0) return err(res, 'Foto tidak ditemukan', 404);
    const existing = eRows[0];
    const { judul, album, status } = req.body;
    let url = existing.url;
    if (req.file) {
      const compressed = await compressImage(req.file.buffer, req.file.originalname);
      url = compressed.url;
    }
    await db.query(
      'UPDATE galeri SET judul=?, album=?, url=?, status=? WHERE id=?',
      [judul || existing.judul, album || existing.album, url, status || existing.status, req.params.id]
    );
    await logActivity('SUCCESS', `Foto galeri diperbarui: ${judul || existing.judul}`, req.user.id, req.ip);
    const [item] = await db.query('SELECT * FROM galeri WHERE id = ?', [req.params.id]);
    ok(res, item[0], 'Foto berhasil diperbarui');
  } catch (e) { next(e); }
});

router.delete('/:id', auth(['Admin']), async (req, res, next) => {
  try {
    const db = getDB();
    const [eRows] = await db.query('SELECT * FROM galeri WHERE id = ?', [req.params.id]);
    if (eRows.length === 0) return err(res, 'Tidak ditemukan', 404);
    if (eRows[0].url && eRows[0].url.startsWith('/uploads/')) {
      const filePath = path.join(__dirname, '..', eRows[0].url);
      if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
    }
    await db.query('DELETE FROM galeri WHERE id = ?', [req.params.id]);
    ok(res, null, 'Foto berhasil dihapus');
  } catch (e) { next(e); }
});

router.post('/bulk-delete', auth(['Admin']), 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');
    const [rows] = await db.query('SELECT url FROM galeri WHERE id IN (?)', [ids]);
    for (const r of rows) {
      if (r.url && r.url.startsWith('/uploads/')) {
        const filePath = path.join(__dirname, '..', r.url);
        if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
      }
    }
    await db.query('DELETE FROM galeri WHERE id IN (?)', [ids]);
    ok(res, null, `${ids.length} foto berhasil dihapus`);
  } catch (e) { next(e); }
});

module.exports = router;
