const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const db = require('../models');
const GalleryImage = db.GalleryImage;

// Create upload directory if not exists
const uploadDir = path.join(__dirname, '../uploads/Gallery');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

// Multer config
const storage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, uploadDir),
  filename: (req, file, cb) => cb(null, Date.now() + '-' + file.originalname)
});
const upload = multer({ storage });

// 📤 Upload image
router.post('/', upload.single('image'), async (req, res) => {
  try {
    const imagePath = `uploads/Gallery/${req.file.filename}`;
    const image = await GalleryImage.create({ imagePath });
    res.status(201).json(image);
  } catch (error) {
    console.error('Upload error:', error);
    res.status(500).json({ message: 'Failed to upload image' });
  }
});

// 📥 Get all images
router.get('/', async (req, res) => {
  try {
    const images = await GalleryImage.findAll({ order: [['createdAt', 'DESC']] });
    res.json(images);
  } catch (error) {
    res.status(500).json({ message: 'Failed to fetch images' });
  }
});

// ❌ Delete image
router.delete('/:id', async (req, res) => {
  try {
    const image = await GalleryImage.findByPk(req.params.id);
    if (!image) return res.status(404).json({ message: 'Image not found' });

    if (fs.existsSync(image.imagePath)) {
      fs.unlinkSync(image.imagePath);
    }

    await image.destroy();
    res.json({ message: 'Image deleted successfully' });
  } catch (error) {
    console.error('Delete error:', error);
    res.status(500).json({ message: 'Failed to delete image' });
  }
});

module.exports = router;
