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 Blog = db.Blog;

// Upload directory setup
const uploadDir = path.join(__dirname, '../uploads/Blogs');
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 });

// POST /api/blogs — Upload blog
router.post('/', upload.fields([{ name: 'image' }, { name: 'pdf' }]), async (req, res) => {
  try {
    const { title } = req.body;
    const image = req.files['image'][0];
    const pdf = req.files['pdf'][0];

    const blog = await Blog.create({
      title,
      imagePath: `uploads/Blogs/${image.filename}`,
      pdfPath: `uploads/Blogs/${pdf.filename}`
    });

    res.status(201).json(blog);
  } catch (err) {
    console.error('Blog upload error:', err);
    res.status(500).json({ message: 'Failed to upload blog' });
  }
});

// GET /api/blogs — Get all blogs
router.get('/', async (req, res) => {
  try {
    const blogs = await Blog.findAll({ order: [['createdAt', 'DESC']] });
    res.json(blogs);
  } catch (err) {
    res.status(500).json({ message: 'Failed to fetch blogs' });
  }
});

// DELETE /api/blogs/:id — Delete blog
router.delete('/:id', async (req, res) => {
  try {
    const blog = await Blog.findByPk(req.params.id);
    if (!blog) return res.status(404).json({ message: 'Blog not found' });

    if (fs.existsSync(blog.imagePath)) fs.unlinkSync(blog.imagePath);
    if (fs.existsSync(blog.pdfPath)) fs.unlinkSync(blog.pdfPath);

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

module.exports = router;
