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

const uploadDir = path.join(__dirname, '../uploads/Home');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

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 });

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

router.get('/', async (req, res) => {
  try {
    const images = await HomeImage.findAll({ order: [['createdAt', 'DESC']] });
    res.json(images);
  } catch (err) {
    res.status(500).json({ message: 'Error fetching images' });
  }
});

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

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

    await image.destroy();
    res.json({ message: 'Deleted successfully' });
  } catch (err) {
    console.error('Delete error:', err);
    res.status(500).json({ message: 'Server error' });
  }
});

module.exports = router;
